views:

318

answers:

2

After reading http://stackoverflow.com/questions/635483/what-is-the-best-way-to-implement-nested-dictionaries-in-python 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?

+7  A: 

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
That was eerily fast, thank you.
Clutch
+1  A: 

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.

Mike Graham