Python dictionary increment Python dictionary increment python python

Python dictionary increment


An alternative is:

my_dict[key] = my_dict.get(key, 0) + num


You have quite a few options. I like using Counter:

>>> from collections import Counter>>> d = Counter()>>> d[12] += 3>>> dCounter({12: 3})

Or defaultdict:

>>> from collections import defaultdict>>> d = defaultdict(int)  # int() == 0, so the default value for each key is 0>>> d[12] += 3>>> ddefaultdict(<function <lambda> at 0x7ff2fe7d37d0>, {12: 3})