Last Updated: February 25, 2016
·
480
· davidcorne

Write or add to an element in a dictionary

I often find myself with the situation where I have a dictionary and I want to add a new value into it.

This is how I used to do it

if (not key in dictionary):
    dictionary[key] = value
else:
    dictionary[key] += value

However, there is a more pythonic way of doing this. Using the setdefault method.

# use "" not 0 if it's string concatenation
dictionary.setdefault(key, 0) 
dictionary[key] += value