When working with Python 3 dictionaries, I keep having to do something like this:
d=dict()
if 'k' in d:
d['k']+=1
else:
d['k']=0
I seem to remember there being a native way to do this, but was looking through the documentation and couldn't find it. Do you know what this is?
This is the use case for collections.defaultdict
, here simply using the int
callable for the default factory.
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> d
defaultdict(<class 'int'>, {})
>>> d['k'] +=1
>>> d
defaultdict(<class 'int'>, {'k': 1})
A defaultdict
is configured to create items whenever a missing key is searched. You provide it with a callable (here int()
) which it uses to produce a default value whenever the lookup with __getitem__
is passed a key that does not exist. This callable is stored in an instance attribute called default_factory
.
If you don't provide a default_factory
, you'll get a KeyError
as per usual for missing keys.
Then suppose you wanted a different default value, perhaps 1 instead of 0. You would simply have to pass a callable that provides your desired starting value, in this case very trivially
>>> d = defaultdict(lambda: 1)
This could obviously also be any regular named function.
It's worth noting however that if in your case you are attempting to just use a dictionary to store the count of particular values, a collections.Counter
is more suitable for the job.
>>> from collections import Counter
>>> Counter('kangaroo')
Counter({'a': 2, 'o': 2, 'n': 1, 'r': 1, 'k': 1, 'g': 1})
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