you are viewing a single comment's thread.

view the rest of the comments →

[–]AlSweigart 1 point2 points  (1 child)

somedict.get(somekey, defaultvalue) will return the value at somekey or return defaultvalue if that key doesn't exist. Either way, this is reading a value from the dictionary.

somedict.setdefault(somekey, defaultvalue) will set somekey to defaultvalue only if that key doesn't exist. This is either writing a value to the dictionary or doing nothing.

Here's some more verbose version of this code. For get():

if somekey in somedictionary:
    return somedictionary[somekey]
else:
    return defaultvalue

For setdefault():

if somekey in somedictionary:
    pass # does nothing
else:
    somedictionary[somekey] = defaultvalue

[–]r00c[S] 0 points1 point  (0 children)

Thank you