Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

defaultdict of defaultdict?

Is there a way to have a defaultdict(defaultdict(int)) in order to make the following code work?

for x in stuff:     d[x.a][x.b] += x.c_int 

d needs to be built ad-hoc, depending on x.a and x.b elements.

I could use:

for x in stuff:     d[x.a,x.b] += x.c_int 

but then I wouldn't be able to use:

d.keys() d[x.a].keys() 
like image 388
Jonathan Livni Avatar asked Feb 17 '11 14:02

Jonathan Livni


People also ask

What does the Defaultdict () function do?

A defaultdict works exactly like a normal dict, but it is initialized with a function (“default factory”) that takes no arguments and provides the default value for a nonexistent key. A defaultdict will never raise a KeyError. Any key that does not exist gets the value returned by the default factory.

What does Defaultdict mean?

Defaultdict is a container like dictionaries present in the module collections. Defaultdict is a sub-class of the dictionary class that returns a dictionary-like object. The functionality of both dictionaries and defaultdict are almost same except for the fact that defaultdict never raises a KeyError.

What is the difference between Defaultdict and dict?

The difference is that a defaultdict will "default" a value if that key has not been set yet. If you didn't use a defaultdict you'd have to check to see if that key exists, and if it doesn't, set it to what you want.


1 Answers

Yes like this:

defaultdict(lambda: defaultdict(int)) 

The argument of a defaultdict (in this case is lambda: defaultdict(int)) will be called when you try to access a key that doesn't exist. The return value of it will be set as the new value of this key, which means in our case the value of d[Key_doesnt_exist] will be defaultdict(int).

If you try to access a key from this last defaultdict i.e. d[Key_doesnt_exist][Key_doesnt_exist] it will return 0, which is the return value of the argument of the last defaultdict i.e. int().

like image 86
mouad Avatar answered Oct 13 '22 22:10

mouad