[Tutor] a better way to express this
Lloyd Kvam
pythontutor@venix.com
Tue, 15 Jan 2002 11:01:01 -0500
dict.setdefault(k,defaultval)
-
requires 2.0 or newer
http://starship.python.net/crew/mwh/hacks/setdefault.html
setdefault
This will initialize the key to the default value when the key is not found in the
dictionary, else it returns the value for the key. I think it is slightly more
general than Danny's solution. A more descriptive name would be:
get_butSetIfMissing(key, defaultvalue)
Danny Yoo wrote:
> 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!
>
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
--
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358
voice:
603-443-6155
fax:
801-459-9582