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
th
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)