🎓 A1Learner
🔍

Python Dictionary Comprehension

A dictionary comprehension builds a new dictionary in one line.

Build a dictionary with a loop

A loop builds the dictionary one pair at a time.

squares = {}
for number in range(1, 5):
    squares[number] = number * number
print(squares)

Build squares in one line

The number is the key. Its square is the value.

squares = {number: number * number for number in range(1, 5)}
print(squares)

Change each value in a dictionary

The loop walks .items(). It builds a new dictionary with doubled prices.

prices = {"pen": 2, "book": 5}
doubled = {item: price * 2 for item, price in prices.items()}
print(doubled)

Add an if filter

The if keeps only even numbers. Odd numbers make no pair.

evens = {number: number * number for number in range(1, 7) if number % 2 == 0}
print(evens)

Pair two sequences with zip

zip() pairs the first name with the first score. It then pairs the next two, and so on.

names = ["Ada", "Bob", "Cy"]
scores = [10, 8, 9]
result = {name: score for name, score in zip(names, scores)}
print(result)

Example

sentence = "the quick brown fox jumps high"
lengths = {word: len(word) for word in sentence.split() if len(word) > 3}
print(lengths)

Key points

  • Dictionary comprehension: {key: value for ...} builds a dictionary in one line.
  • The part left of the colon is the key.
  • The part right of the colon is the value.
  • Add if at the end to keep only matching items.
  • Use zip() to pair two sequences item by item.
  • The Loops section introduced zip().
  • A later value for the same key replaces the earlier pair.

In this example, sentence holds six short words. The split() method cuts it into a list of words. The comprehension takes each word in turn. The if keeps only words longer than 3 letters. Each kept word becomes a key, and len(word) becomes its value. The words the and fox are too short, so they make no pair.

Note

If the loop makes the same key twice, the later value wins.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Which line builds {2: 4, 3: 9} from numbers = [2, 3]?