Paul S. Paul S. - 1 year ago 126
Python Question

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
my_dict[key] = num

Is there a shorter substitute for the four lines above?

Answer Source

An alternative is:

my_dict[key] = my_dict.get(key, 0) + num
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download