What is the difference between dict[key], dict.get(key) and dict.setdefault(key, default)?
d[key] raises KeyError if the key is missing. d.get(key, default) returns the default without changing the dict. d.setdefault(key, default) returns the value and also inserts the default if the key was missing.
Explain it simply
Looking up a name in the college admission register: with [] the clerk shouts "no such student!" (KeyError). With get the clerk says "not found, here is the default answer you gave me" and leaves the register alone. With setdefault the clerk says the same but also writes a new entry for that student.
Example
marks = {"Asha": 80}
print(marks.get("Dev")) # Output: None
print(marks.get("Dev", 0)) # Output: 0
print(marks) # Output: {'Asha': 80}
print(marks.setdefault("Dev", 55)) # Output: 55
print(marks) # Output: {'Asha': 80, 'Dev': 55}
try:
marks["Ira"]
except KeyError:
print("KeyError") # Output: KeyError
groups = {}
for word in ["ant", "bee", "ape"]:
groups.setdefault(word[0], []).append(word)
print(groups) # Output: {'a': ['ant', 'ape'], 'b': ['bee']}What to say in the interview
"Square brackets fail loudly with KeyError, which is right when a missing key is a bug. get returns a default and never modifies the dict. setdefault returns the value and inserts the default when absent, which is handy for grouping, though defaultdict is often cleaner."
Common mistakes
- Using
get(key, [])and then appending, which never stores the new list.