dict.setdefault() — Python Technical Interview Questions & Answers
dict.setdefault()
dict.setdefault()
- dict.setdefault() works on a dictionary — labelled data like marks["Asha"] = 90. Keys map to values. Loop with .items() when you need both.
- dict.setdefault() — output: 90, then 0, then {'Asha': 90, 'Neha': 0}. setdefault adds only if missing.
- Trap for dict.setdefault(): writing d[missing] in a viva. Prefer get when the key might not exist.
{ "Asha": 90, "Ravi": 85 }
│ │
key valueTechnical Interview Tip: get vs [] — one sentence + tiny dict of marks.
Code Examples for dict.setdefault()
Example
# dict.setdefault()
d = {"Asha": 90}
print(d.setdefault("Asha", 0))
print(d.setdefault("Neha", 0))
print(d)
dict.setdefault() — output: 90, then 0, then {'Asha': 90, 'Neha': 0}. setdefault adds only if missing.
How to Explain dict.setdefault() to an Interviewer
Explain dict.setdefault() as if you are teaching a junior — definition, then one tiny script.
dict.setdefault() works on a dictionary. dict.setdefault() — get when key may miss.
What does the example print, and why?
dict
What mistake do freshers make with dict.setdefault()?
dict.setdefault() — d[missing] → KeyError.