Python dictionary increment

Paul S. picture Paul S. · Oct 20, 2012 · Viewed 39.7k times · Source

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?

Answer

Nicola Musatti picture Nicola Musatti · Oct 20, 2012

An alternative is:

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