← Back

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

  1. Scan the literal or construction order and, for each repeated key, keep only the final value.
  2. Compute len() on the collapsed dict β€” duplicates never count twice.
  3. Remember keys compare by equality: 1, 1.0 and True are the same key.
  4. Then evaluate the lookups against the collapsed dict.

Common wrong fixes

Rule to remember

Duplicate keys collapse silently, last value wins, and equality (not identity or type) defines 'duplicate'. Collapse first, then predict.

Solve it in the interactive editor β†’

πŸ“¦ 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