Skip to the solution
EasyBackend13 min read

How do you work with dictionaries (get, setdefault, items, merging)?

1.1k views

The problem

Question presented to candidate: "Walk me through the everyday dictionary toolkit in Python. How do you read a key that might be missing, group items into lists, loop over keys and values, and merge two dictionaries โ€” and which of those have traps?"

What a strong answer should cover:

  • d[key] raises KeyError; d.get(key, default) returns a default instead, and d.get(k) or x is wrong when the stored value is falsy. in tests keys, not values.
  • setdefault(key, default) returns the value and inserts the default first if the key is missing โ€” the classic grouping idiom โ€” but the default expression is evaluated on every call; collections.defaultdict calls its factory only for missing keys.
  • keys(), values() and items() return live views; items() is how you loop over key/value pairs; key views support set operations; deleting while iterating raises RuntimeError.
  • Merging: {**a, **b}, a | b (Python 3.9, PEP 584), a |= b and update() โ€” the right-hand side wins, merging is shallow, and | needs a mapping on the right while |=/update also take an iterable of key/value pairs.
  • Dicts keep insertion order (a language guarantee since 3.7); overwriting a key keeps its position, popitem removes the last item, dict.fromkeys shares one value object.

Code / implementation expected: Yes โ€” a word-grouping or counting snippet, and a config merge with defaults overridden by user values.

  • dict
  • basics

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

13 min read ยท 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

Pythonget vs [], setdefault vs defaultdict, live views and safe deletion
PythonMerging with |, |=, update and **, deep merge, order and fromkeys

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 4 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextEasy

Why use virtual environments?

Continue