Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to natively increment a dictionary element's value?

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?

like image 961
mikeLundquist Avatar asked Jul 20 '16 17:07

mikeLundquist


1 Answers

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})
like image 85
miradulo Avatar answered Oct 15 '22 05:10

miradulo