[英]dynamically populate nested dict in python
I need to populate nested dictionary in python (multiple level of dicts) dynamically inside a for loop.我需要在for循环内动态填充python(多级dicts)中的嵌套字典。 I can only determine the keys dynamically inside for loop.
我只能在 for 循环内动态确定键。 My dict looks like
我的字典看起来像
dict =>
{ bucket1 =>
{classification1 => {key1 : val1, key2 : val2}}
{classification2 => {key1 : val1, key2 : val2}}
} ....
I know the keys bucket1, bucket2 alone as they are fixed values.我只知道键bucket1,bucket2,因为它们是固定值。 So i declare dict[bucket1] = {} and dict[bucket2] = {}.
所以我声明 dict[bucket1] = {} 和 dict[bucket2] = {}。 I try to populate the data inside a for loop as
dict[bucket][classification1][key1] = value
sample block:我尝试将 for 循环内的数据填充为
dict[bucket][classification1][key1] = value
sample block:
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
But I get key error.但我得到关键错误。 I can determine the value of classification1 inside for loop.
我可以在 for 循环中确定 category1 的值。 Hence I cannot declare it intially.
因此我不能一开始就声明它。 Traceback of the error:
错误追溯:
dict['bucket1']['c1']['key1'] = 4
Traceback (most recent call last):
File "<console>", line 1, in <module>
KeyError: 'c1'
What is the efficient way to populate this kind of nested dictionary in python?在python中填充这种嵌套字典的有效方法是什么?
How about doing it with a recursive defaultdict
?用递归
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 } } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.