Interview Q&A / Python
Python interview questions
Lists, dictionaries, generators, decorators and the Python questions asked in service-company and data roles.
Prefer rapid revision? Practise Python short interview answers →
- How do dictionary and set comprehensions work in Python?
A dict comprehension uses curly braces with key: value, as in {k: v for ...}. A set comprehension uses curly braces with one expression, as in {x for ...}, and removes duplicates automatically.
BeginnerQuick answer1 min read - How do you merge two dictionaries in Python?
Use d1 | d2 in Python 3.9+, or {**d1, **d2} in older versions, or d1.update(d2) to modify d1 in place. When both have the same key, the value from the right-hand dictionary wins.
BeginnerQuick answer1 min read - 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.
BeginnerQuick answer1 min read