Home βΊ Problems βΊ Dictionary keys must be unique
Dictionary keys must be unique
π§ Predict the output Topic: dictionaries Difficulty: medium Free
What this problem practises
Dictionaries fail loudly on a missing key with KeyError, quietly through get(), and in genuinely surprising ways when you modify a dict while iterating it or rely on a duplicate key silently replacing the earlier entry.
This is an output-prediction problem: read the snippet carefully and write down exactly what it prints before anything runs. These questions are interview staples because they test whether you know the language rules, or merely recognise their syntax.
Difficulty: medium β expect to hold two interacting rules in your head at once, such as a boundary combined with a mutation.
The challenge
The code runs in PyDebugβs in-browser compiler. Open the problem, run the snippet, watch the exact error or output, and keep iterating until it is right. Signed-in solves count toward XP and your daily streak.
The snippet
The interactive editor pre-fills exactly this code β read it, then submit your prediction:
data = {"a": 1, "b": 2, "a": 3}
print(data)
print(len(data))Understand the rule
A dict literal with the same key twice does not error β the later value silently overwrites the earlier one, so {'a': 1, 'a': 2} is just {'a': 2}, and len() counts unique keys only. The same rule drives dict(zip(...)) with repeated keys and comprehension collisions. Predicting output means collapsing duplicates last-one-wins before reading anything else.
How to trace it
- Scan the literal or construction order and, for each repeated key, keep only the final value.
- Compute len() on the collapsed dict β duplicates never count twice.
- Remember keys compare by equality: 1, 1.0 and True are the same key.
- Then evaluate the lookups against the collapsed dict.
Common wrong fixes
- Expecting a duplicate key in a literal to raise an error or keep the first value; Python keeps the last.
- Counting entries in the source code instead of unique keys for len().
- Missing numeric-key collisions across types: {1: 'a', 1.0: 'b'} has one entry, value 'b'.
Rule to remember
Duplicate keys collapse silently, last value wins, and equality (not identity or type) defines 'duplicate'. Collapse first, then predict.
π¦ Learning path: Lists and Dictionaries
Problem 19 of 20 in this path. Work them in order β each one builds on the rule before it.
β Wrong syntax for adding a new keyNext in path: Nested dictionary access β
πΌ Learning path: Interview Practice
Problem 8 of 16 in this path. Work them in order β each one builds on the rule before it.
β Previous problemNext in path: Dictionary get with a default β
More dictionaries problems
Keep going
- Output-prediction strategies β how to predict tricky snippets without running them.
- Browse every dictionaries problem in this topic.
- Common Python errors and what they actually mean, plus the Python glossary for any term used on this page.