Take the 2-minute tour ×

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


or am I thinking about it wrong?

share|improve this question
add comment

2 Answers

up vote 12 down vote accepted

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]
>>> c[0][0]
share|improve this answer
That was eerily fast, thank you. –  Clutch Mar 24 '10 at 18:03
add comment

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.

share|improve this answer
This is a quality observation. –  Matt Joiner Sep 17 '11 at 12:08
add comment

Your Answer


