Skip to content

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.

Beginner 10 min read·Lesson 148 of 306 in Python Programming

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

Python
lengths = {name: len(name) for name in names}
doubled = {k: v * 2 for k, v in prices.items()}
expensive = {k: v for k, v in prices.items() if v > 100}
inverse = {v: k for k, v in codes.items()}
  • key: value before for.
  • Iterate .items() to transform a dict.
  • Later duplicates overwrite earlier ones.

Code examples

Building a lookup table

Python
names = ["Asha", "Ravi", "Meera"]
print({name: len(name) for name in names})
print({n: n ** 2 for n in range(1, 5)})
Output
{'Asha': 4, 'Ravi': 4, 'Meera': 5}
{1: 1, 2: 4, 3: 9, 4: 16}

Transforming and filtering

Python
prices = {"pen": 20, "bag": 1200, "book": 350}
print({item: round(p * 1.18) for item, p in prices.items()})
print({item: p for item, p in prices.items() if p >= 300})
Output
{'pen': 24, 'bag': 1416, 'book': 413}
{'bag': 1200, 'book': 350}

More examples

zip, inversion and duplicate keys

Python
codes = ["IN", "US", "JP"]
countries = ["India", "United States", "Japan"]
by_code = {c: n for c, n in zip(codes, countries)}
print(by_code)
print({n: c for c, n in by_code.items()})
words = ["apple", "avocado", "banana", "blueberry"]
print({w[0]: w for w in words})
print({w[0]: [x for x in words if x[0] == w[0]] for w in words})
Output
{'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:

TextOutput
{'IN': 'India', 'US': 'United States', 'JP': 'Japan'}
{'India': 'IN', 'United States': 'US', 'Japan': 'JP'}
{'a': 'avocado', 'b': 'blueberry'}
{'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry']}

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

by_city = {p['city']: p for p in people} # one person per city survives

Prefer

Group into lists: collections.defaultdict(list).

Each key can appear only once; earlier values are silently overwritten.

Confusing sets and dicts

Avoid

empty = {} # a dict, not a set

Prefer

empty_set = set()

{} 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

  1. 1
    Build a dictionary mapping each word in a sentence to its number of vowels.
  2. 2
    From 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?
Practise this topic