Python dictionary setdefault - Difference of get and setdefault

Python dictionary setdefault(), which is similar to get(), returns the value of a given key.

d = {
    'book': 97,
    'pen': 145,
}

a = d.setdefault('book')

print(a)  # 97

It's understandable so far.

Set the default value in the dictionary

d = {
    'book': 97,
    'pen': 145,
}

a = d.setdefault('chair', 28)

print(d)  # {'book': 97, 'pen': 145, 'chair': 28}
print(a)  # 28

setdefault() adds the key and value to the dictionary and returns this value if it doesn't have the key. d doesn't have chair so ('chair', 28) is added. get() doesn't add but only return.

  • setdefault() returns the value if the dictionary has the key
  • setdefault() adds the key and value if the dictionary doesn't have the key, and returns the value of new key.

setdefault() is an "advanced" and complex version of get().

Python Dictionary

Python Tutorial