collections.defaultdict
is great. Especially in conjunction with lambda
:
>>> import collections
>>> a = collections.defaultdict(lambda : [None,None])
>>> a['foo']
[None, None]
Is there a way to use the key given (e.g. 'foo'
) in the lambda? For example (doesn't work):
>>> a = collections.defaultdict(lambda : [None]*key)
>>> a[1]
[None]
>>> a[2]
[None, None]
>>> a
defaultdict(<function <lambda> at 0x02984170>, {1: [None], 2: [None, None]})
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.
A common problem that you can face when working with Python dictionaries is to try to access or modify keys that don't exist in the dictionary. This will raise a KeyError and break up your code execution.
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 .
Check If Key Exists using has_key() method Using has_key() method returns true if a given key is available in the dictionary, otherwise, it returns a false. With the Inbuilt method has_key(), use the if statement to check if the key is present in the dictionary or not.
You probably want __missing__
which is called on dict
whenever you try to access an item not present in the dict; the vanilla __missing__
raises an exception, but you could do whatever you like in a subclass:
class A(dict):
def __missing__(self, key):
value = self[key] = [None] * key
return 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