Tricky Dictionary Question from newbie

James Carroll mrmaple at gmail.com
Tue Jul 12 09:09:57 EDT 2005


Notice the dictionary is only changed if the key was missing.

>>> a = {}
>>> a.setdefault("a", "1")
'1'
>>> a.setdefault("a", "2")
'1'
>>> a.setdefault("b", "3")
'3'
>>> a
{'a': '1', 'b': '3'}
>>> a.setdefault("a", "5")
'1'
>>> a
{'a': '1', 'b': '3'}

-Jim

On 7/11/05, Peter Hansen <peter at engcorp.com> wrote:
> 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.)
> 
> -Peter
> --
> http://mail.python.org/mailman/listinfo/python-list
> 
>



More information about the Python-list mailing list