开发者

More nest Python nested dictionaries

开发者 https://www.devze.com 2022-12-23 20:47 出处:网络
After reading What is th开发者_JS百科e best way to implement nested dictionaries? why is it wrong to do:

After reading What is th开发者_JS百科e best way to implement nested dictionaries? why is it wrong to do:

c = collections.defaultdict(collections.defaultdict(int))

in python? I would think this would work to produce

{key:{key:1}}

or am I thinking about it wrong?


The constructor of defaultdict expects a callable. defaultdict(int) is a default dictionary object, not a callable. Using a lambda it can work, however:

c = collections.defaultdict(lambda: collections.defaultdict(int))

This works since what I pass to the outer defaultdict is a callable that creates a new defaultdict when called.

Here's an example:

>>> import collections
>>> c = collections.defaultdict(lambda: collections.defaultdict(int))
>>> c[5][6] += 1
>>> c[5][6]
1
>>> c[0][0]
0
>>> 


Eli Bendersky provides a great direct answer for this question. It might also be better to restructure your data to

>>> import collections
>>> c = collections.defaultdict(int)
>>> c[1, 2] = 'foo'
>>> c[5, 6] = 'bar'
>>> c
defaultdict(<type 'int'>, {(1, 2): 'foo', (5, 6): 'bar'})

depending on what you actually need.

0

精彩评论

暂无评论...
验证码 换一张
取 消