Python 中的多个级别的“collection.defaultdict" [英] Multiple levels of 'collection.defaultdict' in Python
问题描述
感谢 SO 上的一些伟大人物,我发现了 collections.defaultdict
提供的可能性,尤其是在可读性和速度方面.我已经成功地使用了它们.
现在我想实现三个级别的字典,最高的两个是defaultdict
,最低的一个是int
.我没有找到合适的方法来做到这一点.这是我的尝试:
from collections import defaultdictd = defaultdict(defaultdict)a = [("key1", {"a1":22, "a2":33}),(key2",{a1":32,a2":55}),("key3", {"a1":43, "a2":44})]因为我在一个:d[i[0]] = i[1]
现在这有效,但以下是所需的行为,但无效:
d["key4"]["a1"] + 1
我怀疑我应该在某处声明第二级 defaultdict
的类型为 int
,但我没有找到在哪里或如何这样做.>
我首先使用 defaultdict
的原因是为了避免必须为每个新键初始化字典.
还有更优雅的建议吗?
感谢 pythoneers!
使用:
from collections import defaultdictd = defaultdict(lambda: defaultdict(int))
每当在 d
中访问新键时,这将创建一个新的 defaultdict(int)
.
Thanks to some great folks on SO, I discovered the possibilities offered by collections.defaultdict
, notably in readability and speed. I have put them to use with success.
Now I would like to implement three levels of dictionaries, the two top ones being defaultdict
and the lowest one being int
. I don't find the appropriate way to do this. Here is my attempt:
from collections import defaultdict
d = defaultdict(defaultdict)
a = [("key1", {"a1":22, "a2":33}),
("key2", {"a1":32, "a2":55}),
("key3", {"a1":43, "a2":44})]
for i in a:
d[i[0]] = i[1]
Now this works, but the following, which is the desired behavior, doesn't:
d["key4"]["a1"] + 1
I suspect that I should have declared somewhere that the second level defaultdict
is of type int
, but I didn't find where or how to do so.
The reason I am using defaultdict
in the first place is to avoid having to initialize the dictionary for each new key.
Any more elegant suggestion?
Thanks pythoneers!
Use:
from collections import defaultdict
d = defaultdict(lambda: defaultdict(int))
This will create a new defaultdict(int)
whenever a new key is accessed in d
.
这篇关于Python 中的多个级别的“collection.defaultdict"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!