[Tutor] setdefault()

Gregor Lingl glingl at aon.at
Fri Feb 13 17:25:48 EST 2004



Christopher Spears schrieb:

>Can someone clarify what setdefault() does?  I looked
>it up in the docs, and I am still confused.
>
>  
>
If you ask a dictionary for a value for a nonexisting key using setdefault,
the defaultvalue passed to setdefault as the second argument is
- assigned to this key as its value
- AND returned
if you use setdefault with an existing key, nothing is changed and the value
corresponding to this key is returned, i.e. it works lice dic[key]

example:

 >>> dic = {"a":9, "b":-3,"c":0}
 >>> dic["d"]

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in -toplevel-
    dic["d"]
KeyError: 'd'
 >>> dic.setdefault("d",1001)
1001
 >>> dic
{'a': 9, 'c': 0, 'b': -3, 'd': 1001}
 >>> dic.setdefault("a",1001)
9
 >>> dic
{'a': 9, 'c': 0, 'b': -3, 'd': 1001}
 >>>

HTH, Gregor




More information about the Tutor mailing list