Interview Questions
Dictionaries · Study material
Dictionaries – Interview Questions
1. What is a dictionary in Python?
A mutable mapping of unique, hashable keys to values, implemented as a hash table and ordered by insertion (3.7+).
2. Difference between d[key] and d.get(key)?
d[key] raises KeyError for a missing key; get() returns None or a supplied default.
3. What can be a dictionary key?
Any hashable object: str, int, float, bool, tuple of hashables, frozenset. Not lists, dicts or sets.
4. Are dictionaries ordered?
Yes, they preserve insertion order since Python 3.7 (officially), 3.6 in CPython.
5. How do you merge two dictionaries?
a | b (3.9+), {**a, **b}, or a.update(b) in place. Later values win for duplicate keys.
6. What does setdefault() do?
Returns d[key] if present; otherwise inserts key with the default and returns it.
7. What is defaultdict?
A dict subclass that calls a factory (list, int, set …) to create a value for a missing key.
8. How do you sort a dictionary by value?
sorted(d.items(), key=lambda kv: kv[1]), or sorted(d, key=d.get) for the keys.
9. What do keys(), values() and items() return?
Dynamic view objects that reflect later changes to the dictionary.
10. What is the time complexity of dict lookups?
Average O(1); worst case O(n) with many hash collisions.
11. Why is dict.fromkeys(keys, []) dangerous?
All keys share the same list object, so appending through one key changes them all.
12. What happens if you add or delete keys while iterating?
RuntimeError: dictionary changed size during iteration.
13. Why does {1: "a", True: "b"} have one key?
1 == True and they hash equally, so they are the same key; the value is overwritten with "b".
14. How do you find the key with the maximum value?
max(d, key=d.get).
15. What is the difference between pop() and popitem()?
pop(key[, default]) removes a given key; popitem() removes and returns the last inserted pair.