3

After reading What is the 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?

Community
  • 1
  • 1
Clutch
  • 6,774
  • 10
  • 40
  • 54

2 Answers2

14

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
  • 231,995
  • 78
  • 333
  • 394
5

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
  • 64,557
  • 13
  • 91
  • 125