More nest Python nested dictionaries
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.
精彩评论