Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

defaultdict tuple of lists

I like defaultdict, but I want it to autovivify a 2-tuple of lists and I'm not sure if it's possible. So what I want is:

foo = defaultdict(???)
foo['key1'][0].append('value')
foo['key1'][1].append('other value')

is this do-able with defaultdict?

like image 360
xorsyst Avatar asked Feb 17 '14 11:02

xorsyst


People also ask

What does Defaultdict list mean?

defaultdict means that if a key is not found in the dictionary, then instead of a KeyError being thrown, a new entry is created. The type of this new entry is given by the argument of defaultdict.

What is the difference between dict and Defaultdict?

The main difference between defaultdict and dict is that when you try to access or modify a key that's not present in the dictionary, a default value is automatically given to that key . In order to provide this functionality, the Python defaultdict type does two things: It overrides .

How does Defaultdict work Defaultdict forces a dictionary?

A defaultdict can be created by giving its declaration an argument that can have three values; list, set or int. According to the specified data type, the dictionary is created and when any key, that does not exist in the defaultdict is added or accessed, it is assigned a default value as opposed to giving a KeyError .

What is Defaultdict in Python?

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.


1 Answers

Sure. You need to give defaultdict a function that returns what you want the default to be; the easiest way to create such a one-off function is a lambda:

foo = defaultdict(lambda: ([], []))
foo['key1'][0].append('value')
like image 75
RemcoGerlich Avatar answered Sep 17 '22 23:09

RemcoGerlich