I am using 'setdefault()' in my program but I'm not sure what it actually does... so I'm asking on here if anyone one knows?
set default
thanks
The docs are here .
dict.setdefault()
is something like the "lvalue" analog of dict.get()
, which is typically an "rvalue" (occurs on the righthand side of assignments — it retrieves a value, as opposed to mutating the state of something).
Informally, d.setvalue(key, value)
means "Give me d[key]
. What, key
isn't in d
? OK, then assign d[key] = value
, just in time; now give me d[key]
."
Suppose d = {'a': 17}
. Then
>>> d.setdefault('a', 0)
17
Here, 'a'
is in d
, so d.setdefault('a', 0)
leaves d
unchanged and returns d['a']
. However,
>>> d.setdefault('b', 100)
100
Because b
is not in d
, d.setdefault('b', 100)
returns 100 and sets d[b] = 100
. d
now has two items, and both a
and b
are keys:
>>> len(d), d['a'] == 17, d['b'] == 100
(2, True, True)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.