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
Written by David Corne
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Python
Authors
Related Tags
#python
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#