How to update value in dictionary?

Diez B. Roggisch deets at nospam.web.de
Wed Aug 27 09:45:13 EDT 2008


ssecorp wrote:

> dict.update({"a":1}) SETS the dict item "a" 's value to 1.
> 
> i want to increase it by 1. isnt that possible in an easy way? I
> should use a tuple for this?


1) Don't use dict as name for a dictionary, it shadows the type dict

2) setdefault is your friend

d = {}
d['a'] = d.setdefault('a', 1) + 1

Diez





More information about the Python-list mailing list