🐍 Python for Everyone

← Back to challenges

Chapter 8 Interview Prep 19 min read

Interview Questions: Dictionaries & Sets

Dictionaries and sets are where interviewers check whether you understand why Python reaches for hashing instead of scanning — and whether the aliasing/copying traps from Chapter 7 still bite you here. This set covers the practical choice between dict and list, hashability, lookup speed, insertion order, and the set operations that show up constantly in real deduplication work.

1 When would you use a dictionary instead of a list?

Reach for a dictionary when you need to look values up by a meaningful label rather than by position — a user's profile fields, a product catalog keyed by SKU, a word-count table keyed by word. Reach for a list when order and position are what matter, or when there's no natural unique label for each item. The tell is the question you'll ask the collection later: "give me the item at position 3" is a list question; "give me the price for 'eggs'" is a dictionary question.

Simulating a dictionary with two parallel lists (one of keys, one of values) that have to be kept in sync by hand — that's exactly the problem a dict solves natively.

"You need to store each student's grade, looked up by student name. List or dict?" (Dict — grades["Ana"] is a direct label lookup, not a position-based one.)

2 Why must dictionary keys be hashable, and why can't a list be used as one?

A dict finds a key almost instantly by computing a hash — a fixed-size number derived from the key's value — and using it to jump straight to the right storage slot, rather than scanning every entry. For that shortcut to work safely, a key's hash must never change while it's stored, which means the key itself must be immutable. A list is mutable (it can grow, shrink, or have elements reassigned at any time), so its hash would have to change too, and Python simply refuses: hash([1, 2]) raises TypeError. Tuples, strings, and numbers are all immutable and hashable, so they're all valid keys.

Saying "lists just aren't allowed as keys" without connecting it back to mutability and hashing — that's the actual mechanism, not an arbitrary rule.

"Would a tuple containing a list, like (1, [2, 3]), be a valid dict key?" (No — a container is only hashable if every element inside it is also hashable; the mutable list inside makes the whole tuple unhashable too.)

3 What's the difference between my_dict["key"] and my_dict.get("key") when the key is missing?

Square-bracket access, my_dict["key"], raises a KeyError immediately if the key doesn't exist — the program crashes right there unless something catches it. my_dict.get("key") instead returns None for a missing key, with no error at all, and my_dict.get("key", default) lets you supply your own fallback value instead of None. .get() is the safer default any time a missing key is a normal, expected possibility rather than a bug — e.g. looking up an optional field on a user record.

Reaching for square brackets everywhere and then wrapping every single lookup defensively, instead of just using .get() with a sensible default when a missing key is expected.

"Given d = {'a': 1}, what does d.get('z', 0) return?" (0 — the fallback value, since 'z' isn't a key in d.)

4 How would you check whether a key exists in a dictionary before using it?

Use the in operator: if "sku" in inventory: checks membership among the dict's keys and reads cleanly before doing a lookup you know is safe. This is the same in operator used for lists and strings, but on a dict it only ever checks keys, never values — 1 in {"a": 1} is False, even though 1 is a value in that dict. Combining in with square brackets (if k in d: x = d[k]) is a common, perfectly valid alternative to .get() when you need to branch on whether the key existed at all, not just get a fallback value.

Assuming in on a dict searches values — it only searches keys.

"Given d = {'a': 1}, what does 1 in d evaluate to?" (False — in checks keys, and 1 is a value, not a key, in this dict.)

5 Why is a dictionary lookup considered fast even for a huge dictionary, while searching a huge list is slow?

Checking x in my_list has to scan element by element from the start until it finds a match or reaches the end — on average, that scan gets longer as the list gets bigger. Checking x in my_dict (or my_set) instead computes the hash of x and jumps almost directly to the slot where it would live, so the lookup takes roughly the same tiny amount of time whether the dict has 10 entries or 10 million. That's the practical reason dicts and sets are the go-to structure for "have I seen this before?" checks and deduplication, especially inside a loop where a list-based check would silently turn into a much slower operation as data grows.

Treating list membership checks and dict/set membership checks as equally fast regardless of collection size — that assumption falls apart the moment the collection gets large and the check runs inside a loop.

"You need to check thousands of times whether an ID has already been seen. List or set for the 'seen IDs' collection?" (Set — membership checks are effectively instant regardless of how many IDs have been seen, unlike a list which re-scans every time.)

6 Does a Python dictionary remember the order keys were inserted in?

Yes — modern Python dictionaries preserve insertion order: looping over a dict's keys, values, or items always visits them in the order they were first added, not some scrambled or sorted order. This is a real, relied-upon language guarantee (not an implementation accident) as of Python 3.7+. It's worth knowing that insertion order is not the same as sorted order — if you need keys in alphabetical or numeric order, you still have to call sorted() on them explicitly.

Assuming dict order is random or assuming it's automatically sorted — it's neither; it's strictly insertion order until you sort it yourself.

"After d = {}, d['z'] = 1, d['a'] = 2, what order do the keys print in?" (z then a — insertion order, not alphabetical order.)

7 What's the difference between .keys(), .values(), and .items()?

.keys() gives every key in the dict, .values() gives every value, and .items() gives every (key, value) pair as a tuple — all three preserve insertion order and all three are the standard way to loop over a dict depending on what you need. for k in d: alone already loops over keys (the same as for k in d.keys()), so .keys() is often skipped in a plain key loop; .items() is the one that gets used constantly, since for key, value in d.items(): unpacks both in one line, mirroring the pair-unpacking idiom from Chapter 7.

Looping with for k in d: and then manually re-looking-up d[k] inside the loop when .items() would hand back both directly.

"How would you loop over prices = {'egg': 3, 'milk': 4} and print each item and its price on one line?" (for item, price in prices.items(): print(item, price).)

8 What happens if you assign to a key that already exists in a dictionary?

Assignment always overwrites — my_dict["a"] = new_value silently replaces whatever value was previously stored under "a", with no warning or error, whether the key existed before or not. This is also exactly what .update() does across many keys at once: d1.update(d2) copies every key/value pair from d2 into d1, overwriting any key that already existed in d1 and adding any that didn't. There's no built-in protection against accidentally clobbering an existing value this way — if that matters, you check with in first.

Expecting an error or a warning when overwriting an existing key — Python does it silently every time.

"Given d = {'a': 1} and d.update({'a': 2, 'b': 3}), what is d afterward?" ({'a': 2, 'b': 3} — the existing key 'a' got overwritten, and the new key 'b' got added.)

9 What's the difference between .pop("key") and del my_dict["key"]?

Both remove a key/value pair from the dict, but .pop("key") also returns the removed value so you can capture and use it, while del my_dict["key"] just deletes it and gives nothing back. .pop("key", default) additionally lets you supply a fallback instead of raising KeyError if the key isn't present — the same safety pattern as .get(). del has no such safety net on a plain dict; deleting a missing key with del raises KeyError every time.

Using del when you actually need the removed value back, or forgetting that both raise KeyError on a missing key unless .pop() is given an explicit default.

"Given d = {'a': 1, 'b': 2}, what does d.pop('z', 'N/A') return, and does it raise an error?" (Returns 'N/A', no error — the default absorbs the missing key.)

10 What's the difference between == and is when comparing two dictionaries?

Just like with lists in Chapter 7, == compares values — two separately built dicts with the same keys mapped to the same values are ==, regardless of insertion order. is compares identity — whether both names point at the exact same object in memory. Two dicts built independently with identical contents are essentially never is the same object, even though they're ==. This matters because dicts are mutable, so the aliasing trap from Chapter 7 (b = a makes b and a the same object) applies to dicts exactly the same way.

Using is to check whether two dicts have the same contents — that's what == is for.

"Are {'a': 1} and {'a': 1}, written as two separate literals, the same object?" (No — each dict literal creates a new object, so they're == but not is.)

11 What's the gotcha with a shallow copy of a dictionary that contains nested dicts or lists?

Just like the nested-list shallow-copy trap in Chapter 7, copy = original.copy() only copies the outer dictionary — any value inside it that's itself mutable (a nested dict or list) is still the exact same shared object in both copies. So if original = {"scores": [10, 20]} and you make a shallow copy, appending to copy["scores"] silently changes original["scores"] too, because there's really only one list object being pointed at by both dicts. The fix at this course's level is rebuilding the nested structure by hand (a fresh inner dict or list per record) rather than assuming .copy() makes everything independent.

Calling .copy() on a dict of records and assuming every nested value is now independent — only the top-level dict is.

"After original = {'a': [1, 2]}, shallow = original.copy(), shallow['a'].append(3) — what is original?" ({'a': [1, 2, 3]} — the inner list is shared between both dicts, so mutating it through shallow also changes original.)

12 What's a set, and what's it good for that a list isn't?

A set is an unordered collection of unique, hashable values — duplicates are automatically dropped, and there's no positional indexing the way a list has. The two things a set is genuinely better at than a list: instant membership checks (the same hashing shortcut dicts use), and free deduplication — set([1, 1, 2, 2, 3]) collapses straight to {1, 2, 3} with zero extra code. Real use cases include tracking unique visitor IDs seen so far, collecting the distinct tags used across a set of posts, or removing duplicate entries from a list of scraped values.

Reaching for a list plus a manual "have I already added this?" check inside a loop when a set would deduplicate automatically and check membership instantly.

"What does set([1, 2, 2, 3, 3, 3]) evaluate to?" ({1, 2, 3} — every duplicate collapses to a single entry.)

13 What do |, &, and - do between two sets?

set_a | set_b is the union — every element that appears in either set, with duplicates naturally collapsed. set_a & set_b is the intersection — only elements present in both sets. set_a - set_b is the difference — elements in set_a that are not in set_b. These map directly onto real questions like "which visitors came on both Monday and Tuesday" (intersection), "which visitors came on either day" (union), or "which visitors from Monday never came back on Tuesday" (difference) — the kind of comparison that would take nested loops on two lists but is one operator on two sets.

Mixing up intersection and difference, or trying to write a manual nested loop to compare two collections for overlap when a set operation already does it directly.

"Given monday = {'u1', 'u2', 'u3'} and tuesday = {'u2', 'u3', 'u4'}, what is monday - tuesday?" ({'u1'} — the visitor who came Monday but not Tuesday.)

14 What's the difference between .remove() and .discard() on a set?

Both delete an element from a set, but .remove(x) raises a KeyError if x isn't present, while .discard(x) does nothing at all if x isn't present — no error either way. Use .discard() when "it might already be gone" is a normal, expected case (e.g. removing a visitor ID that may or may not have been tracked yet); use .remove() when you specifically want to be alerted that the element you expected to be there wasn't. This mirrors the .get()-vs-square-brackets safety distinction for dicts, just phrased as two different methods instead of two different access styles.

Using .remove() on a set where the element's presence isn't guaranteed, then being surprised by an unhandled KeyError.

"Given tags = {'a', 'b'}, what happens when you call tags.discard('z')?" (Nothing — 'z' isn't in the set, and .discard() silently does nothing instead of raising an error.)

Rapid-Fire Review

Quick recall check — fill in each blank and hit Check.

🎉 Perfect score — you're ready to talk about this chapter in an interview.
← Challenges Build the Project →