从python字典和嵌套字典/列表中构建一个Json文件。

时间:2021-06-05 20:30:44

I am having hard time to build a json file. That should look like:

我很难构建json文件。这应该看起来像:

{'January': 
     [ {'week 1' : 
        [ {'day 1': [{'birthday_name': 'Stack', 'lastname': 'hector'},{'birthday_name': 'Stack', 'lastname': 'hector'},
          {'day 2': [{'birthday_name': 'Vlad', 'lastname': 'Overflow'},{'birthday_name': 'Exchange', 'lastname': 'Other'} ]
        }
      ],
     [ {'week 2' : 
        [ {'day 1': [{'birthday_name': 'Stack', 'lastname': 'hector'},{'birthday_name': 'Stack', 'lastname': 'hector'},
          {'day 2': [{'birthday_name': 'Vlad', 'lastname': 'Overflow'},{'birthday_name': 'Exchange', 'lastname': 'Other'} ]
        }
      ]
 }  

I have this code for now, but since I am building when the loop occurs there is value that do not exist yet like month, week and day. I am trying with if statement to check if the dictionnary value exist, if yes continue down the tree and check if there is the week and the day if yes to all three then append the value. If not for each of them I create the value in the dictionary/list to make it available to fill then the data.

我现在已经有了这段代码,但是由于我正在构建循环时,有一些值还不存在,比如月、周和日。我正在尝试使用if语句来检查dictionnary值是否存在,如果是,继续沿着树查看是否有周和日,如果是,则将值追加。如果不是每个值,我就在字典/列表中创建值,以便填充数据。

And now I get error code 'KeyError'. (value does not exist in dictionary)

现在我得到了错误代码“KeyError”。(值在字典中不存在)

here is the code for now.

这是现在的代码。

final_list = {}

for i in friends:
    friends_name = i['SUMMARY'][16:]
    friends_bdate = i['DTSTART']
    month_bday = int(i['DTSTART'][4:6])
    day_bday = int(i['DTSTART'][6:8])
    week_number = datetime.date(2015, month_bday, day_bday).isocalendar()[1]


    if final_list[month_bday]:
        if final_list[month_bday][week_number]:
            if final_list[month_bday][week_number][day_bday]:
                final_list[month_bday][week_number][day_bday].append({'name': friends_name, 'bdate': friends_bdate, 'pic' : friends_picture})
            else:
                final_list[month_bday] = [{week_number: [{day_bday: []}]}]
                final_list[month_bday][week_number][day_bday].append({'name': friends_name, 'bdate': friends_bdate, 'pic' : friends_picture})
        else:
            final_list[month_bday] = [{week_number: []}]
            if final_list[month_bday][week_number][day_bday] :
                final_list[month_bday][week_number][day_bday].append({'name': friends_name, 'bdate': friends_bdate, 'pic' : friends_picture})
            else:
                final_list[month_bday] = [{week_number: [{day_bday: []}]}]
                final_list[month_bday][week_number][day_bday].append({'name': friends_name, 'bdate': friends_bdate, 'pic' : friends_picture})
    else:
        final_list[month_bday] = {month_bday : []}
        if final_list[month_bday][week_number]:
            if final_list[month_bday][week_number][day_bday]:
                final_list[month_bday][week_number][day_bday].append({'name': friends_name, 'bdate': friends_bdate, 'pic' : friends_picture})
            else:
                final_list[month_bday] = [{week_number: [{day_bday: []}]}]
                final_list[month_bday][week_number][day_bday].append({'name': friends_name, 'bdate': friends_bdate, 'pic' : friends_picture})
        else:
            final_list[month_bday] = [{week_number: []}]
            if final_list[month_bday][week_number][day_bday] :
                final_list[month_bday][week_number][day_bday].append({'name': friends_name, 'bdate': friends_bdate, 'pic' : friends_picture})
            else:
                final_list[month_bday] = [{week_number: [{day_bday: []}]}]
                final_list[month_bday][week_number][day_bday].append({'name': friends_name, 'bdate': friends_bdate, 'pic' : friends_picture})           

edit: the others variable are: friends_name = 'Tony' friends_bday = '20150516'

编辑:其他变量是:friends_name = 'Tony' friends_bday = '20150516'

Thank for Daniel answer I just changed this

谢谢丹尼尔的回答,我只是改变了这个。

final_list = defaultdict(lambda: defaultdict(lambda: {}))

to

final_list = defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: {})))

link to defaultdict function. https://docs.python.org/2/library/collections.html#collections.defaultdict

defaultdict链接功能。https://docs.python.org/2/library/collections.html collections.defaultdict

1 个解决方案

#1


1  

Use defaultdicts and datetime.strptime:

使用defaultdicts datetime.strptime:

from collections import defaultdict
final_list = defaultdict(lambda: defaultdict(lambda: {}))

for friend in friends:
    friends_name = friend['SUMMARY'][16:]
    friends_bdate = datetime.datetime.strptime(friend['DTSTART'], '%Y%m%d')
    week_number = friends_bdate.replace(year=2015).isocalendar()[1]
    final_list[friends_bdate.month][week_number][friends_bdate.day] = {
        'name': friends_name, 'bdate': friend['DTSTART'], 'pic' : friends_picture
    }

#1


1  

Use defaultdicts and datetime.strptime:

使用defaultdicts datetime.strptime:

from collections import defaultdict
final_list = defaultdict(lambda: defaultdict(lambda: {}))

for friend in friends:
    friends_name = friend['SUMMARY'][16:]
    friends_bdate = datetime.datetime.strptime(friend['DTSTART'], '%Y%m%d')
    week_number = friends_bdate.replace(year=2015).isocalendar()[1]
    final_list[friends_bdate.month][week_number][friends_bdate.day] = {
        'name': friends_name, 'bdate': friend['DTSTART'], 'pic' : friends_picture
    }