Python中多个级别的“collection.defaultdict” [英] Multiple levels of 'collection.defaultdict' in Python

查看:352
本文介绍了Python中多个级别的“collection.defaultdict”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感谢SO上的一些好人,我发现了 collections.defaultdict 提供的可能性和速度。我已经让他们成功使用了。



现在我想实现三个级别的字典,两个顶级的字典是 defaultdict ,最低的一个是 int 。我没有找到适当的方法来做到这一点。这是我的尝试:

 从集合import defaultdict 
d = defaultdict(defaultdict)
a = [( (key2,{a1:32,a2:55}),
(key3 ,{a1:43,a2:44})]
在我的a:
d [i [0]] = i [1]

现在这样做,但以下是所需的行为,不会:

  d [key4] [a1] + 1 



我怀疑我应该声明第二级 defaultdict 的类型是 int ,但我没有没有找到在哪里或如何这样做。



首先我使用 defaultdict 的原因是避免不必为每个新密钥初始化字典。



任何更优雅的建议?



感谢pythoneers! / p>

解决方案

使用:

  d = defaultdict(lambda:defaultdict(int))

每当有一个新的 defaultdict(int)新密钥在 d 中访问。


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:

d = defaultdict(lambda: defaultdict(int))

This will create a new defaultdict(int) whenever a new key is accessed in d.

这篇关于Python中多个级别的“collection.defaultdict”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆