Python dictionary increment

45,742

Solution 1

An alternative is:

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

Solution 2

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

>>> from collections import Counter
>>> d = Counter()
>>> d[12] += 3
>>> d
Counter({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
>>> d
defaultdict(<function <lambda> at 0x7ff2fe7d37d0>, {12: 3})

Solution 3

What you want is called a defaultdict

See http://docs.python.org/library/collections.html#collections.defaultdict

Solution 4

transform:

if key in my_dict:
  my_dict[key] += num
else:
  my_dict[key] = num

into the following using setdefault:

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

Solution 5

There is also a little bit different setdefault way:

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

Which may have some advantages if combined with other logic.

Share:
45,742
Paul S.
Author by

Paul S.

Updated on July 09, 2022

Comments

  • Paul S.
    Paul S. almost 2 years

    In Python it's annoying to have to check whether a key is in the dictionary first before incrementing it:

    if key in my_dict:
      my_dict[key] += num
    else:
      my_dict[key] = num
    

    Is there a shorter substitute for the four lines above?

    • Mohsin
      Mohsin almost 7 years
      can you do this same thing for two values?
  • hughdbrown
    hughdbrown over 11 years
    For lambda: 0, you can just say, int.
  • Blender
    Blender over 11 years
    @hughdbrown: Thanks, I never knew that.
  • Noel Evans
    Noel Evans over 8 years
    @hughdbrown without your comment I would never have understood what a defaultdict was doing. Thank you.
  • Mohsin
    Mohsin almost 7 years
    can you do it for multiple values? i mean increment more than one value
  • Nicola Musatti
    Nicola Musatti almost 7 years
    Without a loop? As dict doesn't provide a way to access multiple elements in a single expression I don't see how.
  • Mohsin
    Mohsin almost 7 years
    With a loop just like the OP writes in his question, but incrementing two values per key not one
  • Nicola Musatti
    Nicola Musatti almost 7 years
    I think you should ask a new question for that.
  • Czechnology
    Czechnology over 6 years
    It's a pity that the docs don't mention that Counter also supports the default 0 functionality. I have been using Nicola's solution until now, but it's much nicer without it.