How does .setdefault() work?

后端 未结 1 846
情深已故
情深已故 2021-01-28 00:56

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

相关标签:
1条回答
  • 2021-01-28 01:01

    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)
    
    0 讨论(0)
提交回复
热议问题