Tricky Dictionary Question from newbie

Peter Hansen peter at
Tue Jul 12 05:34:10 CEST 2005

Ric Da Force wrote:
> How does setdefault work exactly? I am looking in the docs and can't figure 
> it out...

If the key (the first argument) already exists in the dictionary, the 
corresponding value is returned.  If the key does not exist in the 
dictionary, it is stored in the dictionary and bound to the second 
argument, and then that second argument is returned as the value.

(I always have to ignore the name to think about how it works, or it 
gets in the way of my understanding it.  The name makes fairly little 
sense to me.)


More information about the Python-list mailing list