Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dictionary increment

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?

like image 410
Paul S. Avatar asked Oct 20 '12 20:10

Paul S.


People also ask

How do you increment by 1 in Python?

Python increment operator In python, if you want to increment a variable we can use “+=” or we can simply reassign it “x=x+1” to increment a variable value by 1.

What is .get in Python?

Python Dictionary get() Method The get() method returns the value of the item with the specified key.

Is there append in dictionary Python?

The Python dictionary offers an update() method that allows us to append a dictionary to another dictionary. The update() method automatically overwrites the values of any existing keys with the new ones.


1 Answers

An alternative is:

my_dict[key] = my_dict.get(key, 0) + num 
like image 197
Nicola Musatti Avatar answered Sep 29 '22 08:09

Nicola Musatti