在Python中动态填充嵌套字典

时间:2019-12-06 19:13:44

标签: python dictionary

我需要在for循环内动态地在python(多级字典)中填充嵌套字典。我只能在for循环中动态确定键。我的字典看起来像

dict =>
    { bucket1 => 
                {classification1 => {key1 : val1, key2 : val2}}
                {classification2 => {key1 : val1, key2 : val2}}
    } ....

我知道键bucket1,bucket2本身就是固定值。因此,我声明dict [bucket1] = {}和dict [bucket2] = {}。我尝试将for循环内的数据填充为dict[bucket][classification1][key1] = value示例块:

for string in stringarray:
    bucket = "some string based on regex" #this can be fixed set of 2 strings
    classification = "some string based on regex"
    key = "some string based on regex"
    value = "count of the occurence of [classification1][key1]"
    dict[bucket][classification][key] = value

但是我得到关键错误。我可以确定for循环内的category1的值。因此,我不能一开始就声明它。错误的回溯:

    dict['bucket1']['c1']['key1'] = 4
Traceback (most recent call last):
  File "<console>", line 1, in <module>
KeyError: 'c1'

在python中填充这种嵌套字典的有效方法是什么?

1 个答案:

答案 0 :(得分:0)

如何使用递归defaultdict来做到这一点?

from collections import defaultdict

recursive_dict = lambda: defaultdict(recursive_dict)
my_dict = recursive_dict()

bucket = "bucket"
classification = "class"
key = "key"
value = 2
my_dict[bucket][classification][key] = value
# my_dict ==> { "bucket": { "class": { "key": 2 } } }