0

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

  • 1
    Possible duplicate of [Use cases for the 'setdefault' dict method](http://stackoverflow.com/questions/3483520/use-cases-for-the-setdefault-dict-method) – JDurstberger Feb 12 '16 at 11:11
  • 1
    Did you look at the [Python documentation](https://docs.python.org/3.5/library/stdtypes.html#dict.setdefault) already? If so, please indicate which part of that documentation you need help understanding. (And if not, please do!) – Mark Dickinson Feb 12 '16 at 11:25
  • As an aside, it's not a good idea to use things in your program(s) that you don't understand. The goal is to understand your program and have a (correct!) mental model of how it works. So, +1 for asking. – BrianO Feb 12 '16 at 12:24

1 Answers1

2

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)
BrianO
  • 1,496
  • 9
  • 12