dict.clear() — Python Technical Interview Questions & Answers
dict.clear()
dict.clear()
- dict.clear() works on a dictionary — labelled data like marks["Asha"] = 90. Keys map to values. Loop with .items() when you need both.
- dict.clear() — output: {}.
- Trap for dict.clear(): 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.clear()
Example
# dict.clear()
d = {"a": 1}
d.clear()
print(d)
dict.clear() — output: {}.
How to Explain dict.clear() to an Interviewer
Explain dict.clear() as if you are teaching a junior — definition, then one tiny script.
dict.clear() works on a dictionary. dict.clear() — get when key may miss.
What does the example print, and why?
dict
What mistake do freshers make with dict.clear()?
dict.clear() — d[missing] → KeyError.