How to make a nested dictionary and dynamically append data

前端 未结 5 1146
闹比i
闹比i 2021-01-13 02:16

I have a loop giving me three variables

matteGroup
matteName
object

I would like to make a nested dicionary holding all the data like:

5条回答
  •  清歌不尽
    2021-01-13 02:32

    Due to an issue with pickling my object, that used some of the previous answers, I tried to solve this as well. This is what worked for me for dynamically adding new keys to two different sub levels of dictionaries:

    from collections import defaultdict
    test = defaultdict(defaultdict)
    test["level1"]["level2"] = 1
    test["level1"]["level2_second"] = 2
    print(test)
    

    defaultdict(, {'level1': defaultdict(None, {'level2': 1, 'level2_second': 2})})

    This solution seems to be only able to handle two levels of nesting.

提交回复
热议问题