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?
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.
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 .
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 .
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.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With