I\'ve read the examples in python docs, but still can\'t figure out what this method means. Can somebody help? Here are two examples from the python docs
>
My own 2¢: you can also subclass defaultdict:
class MyDict(defaultdict):
def __missing__(self, key):
value = [None, None]
self[key] = value
return value
This could come in handy for very complex cases.
There is a great explanation of defaultdicts here: http://ludovf.net/blog/python-collections-defaultdict/
Basically, the parameters int and list are functions that you pass. Remember that Python accepts function names as arguments. int returns 0 by default and list returns an empty list when called with parentheses.
In normal dictionaries, if in your example I try calling d[a]
, I will get an error (KeyError), since only keys m, s, i and p exist and key a has not been initialized. But in a defaultdict, it takes a function name as an argument, when you try to use a key that has not been initialized, it simply calls the function you passed in and assigns its return value as the value of the new key.
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.
For example:
somedict = {}
print(somedict[3]) # KeyError
someddict = defaultdict(int)
print(someddict[3]) # print int(), thus 0