Module 10 · Comprehensions and Advanced Iteration — topic 4 of 13
Dictionary comprehensions
Building dictionaries with {key: value for ...}: from lists, from zip, inverting and filtering dictionaries, and handling duplicate keys.
Learning objectives
- Create dictionaries with comprehensions
- Transform and filter existing dictionaries
- Predict what happens with duplicate keys
Definition
A dictionary comprehension is an expression {key_expr: value_expr for item in iterable} that builds a new dictionary, evaluating a key and a value for each item.
Introduction
{name: len(name) for name in names} maps each name to its length in one line. Dictionary comprehensions are the dictionary equivalent of list comprehensions.
Why it matters
Lookup tables, indexes, renaming and filtering of dictionaries come up constantly when working with data and JSON.
Detailed explanation
The form is {key: value for item in iterable}, optionally with if filters, exactly like list comprehensions.
To transform an existing dictionary, iterate over d.items(): {k: v * 2 for k, v in d.items()}.
To combine two lists into a dictionary, zip them: {k: v for k, v in zip(keys, values)} — or simply dict(zip(keys, values)).
If the same key is produced twice, the later value wins, because dictionaries can't hold duplicate keys.
Inverting a dictionary ({v: k for k, v in d.items()}) only works safely when values are unique and hashable.
Note the braces: {x for x in items} without a colon is a set comprehension, not a dictionary.
Syntax
- key: value before for.
- Iterate .items() to transform a dict.
- Later duplicates overwrite earlier ones.
Code examples
Building a lookup table
{'Asha': 4, 'Ravi': 4, 'Meera': 5}
{1: 1, 2: 4, 3: 9, 4: 16}Transforming and filtering
{'pen': 24, 'bag': 1416, 'book': 413}
{'bag': 1200, 'book': 350}More examples
zip, inversion and duplicate keys
{'IN': 'India', 'US': 'United States', 'JP': 'Japan'}
{'India': 'IN', 'United States': 'US', 'Japan': 'JP'}
{'a': 'avocado', 'b': 'blueberry'}
{'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry']}Step-by-step explanation
- zip pairs codes with names, and the comprehension turns the pairs into a dictionary.
- Swapping k and v inverts it, which is safe because the values are unique.
- With first letters as keys, apple is overwritten by avocado: later values win.
- Grouping keeps everything by building a list for each key (a defaultdict loop is more efficient for large data).
Expected output
Running “zip, inversion and duplicate keys” prints exactly:
Practical applications
- Indexing records by id: {u['id']: u for u in users}.
- Renaming or cleaning JSON keys.
- Building translation and lookup tables.
Best practices
- Use dict(zip(a, b)) when no transformation is needed.
- Check that keys are unique before inverting.
- Group with defaultdict instead of nested comprehensions for large data.
Common mistakes
Losing data to duplicate keys
Avoid
Prefer
Each key can appear only once; earlier values are silently overwritten.
Confusing sets and dicts
Avoid
Prefer
{} is an empty dictionary; use set() for an empty set.
Important notes
- Dictionaries keep insertion order (Python 3.7+), so comprehensions preserve the order of the source.
Key takeaways
- {k: v for ...} builds a dictionary.
- Iterate .items() to transform or filter one.
- Duplicate keys keep the last value.
Try it yourself
- 1Build a dictionary mapping each word in a sentence to its number of vowels.
- 2From a dictionary of marks, build one containing only students who scored above 75.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
1 question test this exact topic. Answers and explanations are revealed after you submit.
- ModerateWhat is printed?