[Tutor] a better way to express this

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Mon, 14 Jan 2002 17:38:53 -0800 (PST)


On Mon, 14 Jan 2002, Sean 'Shaleh' Perry wrote:

> So today I must have typed the following about 10 times:
> 
> if dict.has_key(key):
>     dict[key] = dict[key] + 1 # or maybe foo.data
> else:
>     dict[key] = 1 # or maybe foo.data
> 
> Is there no better way to code that?

Actually, there is!

###
dict[key] = dict.get(key, 0) + 1
###

The get() method of dictionaries support an optional "default" value than
you can specify if the element's not in the dictionary.


Hope this helps!