This is how defaultdict works:
from collections import defaultdict
a=defaultdict(lambda:3)
a[200]==3 #True
Why is it that defaultdict
was designed to take a function with no arguments, and not simply a constant value?
Here's the alternative definition.
class dd(dict):
def __init__(self,x):
self._default=x
def __getitem__(self,key):
if key in self: return dict.__getitem__(self, key)
else:
self[key]=self._default
return self[key]
So that
a=dd(3)
a[200]==3 #True
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.
The functionality of both dictionaries and defaultdict are almost the same except for the fact that defaultdict never raises a KeyError. It provides a default value for the key that does not exist. Parameters: default_factory: A function returning the default value for the dictionary defined.
setdefault() , and the second uses a defaultdict . The time measure will depend on your current hardware, but you can see here that defaultdict is faster than dict.
The defaultdict is a subdivision of the dict class. Its importance lies in the fact that it allows each new key to be given a default value based on the type of dictionary being created. A defaultdict can be created by giving its declaration an argument that can have three values; list, set or int.
Because if you want the default value to be a mutable object, you probably want it to be a different mutable object for each key.
If you passed a constant and did defaultdict([])
, then every time a missing key was accessed, its value would be set to the same list. Then you'd get this:
>>> d = defaultdict([])
>>> d[1].append("Whoops")
>>> print d[2]
["Whoops"]
Having a mutable default value is in fact very common and useful, since it lets you do things like d[key].append("Blah")
without having to first check that d[key]
exists. For this case, you need some way to return a new value each time, and the simplest way to do that is to have a callable that returns a default 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