Additional Python sockets nested dictionaries

After reading What is the best way to implement nested dictionaries? why this is wrong:

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

in python? I would have thought it would work to produce

{key:{key:1}}

or am I thinking about it wrong?

+3
source share
2 answers

The constructor defaultdictexpects the called. defaultdict(int)is the default dictionary, not called. Using lambda, it can work, however:

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

This works because what I pass to the external defaultdictis the callable, which creates a new one defaultdictwhen called.

Here is an example:

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

. ,

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

, .

+5

Source: https://habr.com/ru/post/1738374/


All Articles