【问题标题】:Printing nested dictionary loop YYYYMMDD打印嵌套字典循环 YYYYMMDD
【发布时间】:2020-04-17 10:13:52
【问题描述】:

请帮助,这里的新手。我想遍历一个月中的每一天,并以 YYYYMMDD 格式打印日期,例如。 20150203 表示 2015 年 2 月的第三天。

initial_values = {'year': 2015}

calendar_5 = {initial_values['year']: {"01": 31, "02": 28}}

for day in range(calendar_5[initial_values['year']]["02"]):
    for year in calendar_5:
        for month, day in calendar_5.items():
            print(calendar_5[initial_values[month]][day])

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    您应该考虑重新构建您的字典,您的数据结构包含冗余数据并且不支持每月多天。主字典可能有年份作为这样的键:

    • 字典就像year: month_dict
    • 每个month_dict 都有月份作为键,月份日期列表作为值。

    例如,你需要的字典可能是这样的:

    my_dict = {
        '2019': {
            '1': [2, 14, 30], # January
            '5': [5, 11, 13]  # May
        }
        '2020': {
            '12': [9] # December
        }
    }
    

    这样,打印起来真的很容易:

    for year, month_dict in my_dict.items():
        for month, list_days in month_dict.items():
            for day in list_days:
                print('{}{}{}'.format(year, month, day)
    

    【讨论】:

    • 您不需要创建自己的字典。 Python 内置了日历操作库docs.python.org/3/library/calendar.html.
    • 当然!但是我们不知道他是否可能从文本文件或其他来源获取数据,所以我想给出答案,这样它就更灵活了。但是,是的,这也是事实。
    • 我从一个文本文件中获取它——我知道日历库,但我正在学习,所以我想自己做。非常感谢您的帮助@Cblopez!它很灵活,我认为它真的很有帮助:)
    猜你喜欢
    • 2017-07-22
    • 2022-06-15
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    • 1970-01-01
    • 2021-05-30
    相关资源
    最近更新 更多