← Python lessons

Python Dictionary Comprehension (Plus Set Comprehension)

A dictionary comprehension builds a dictionary in one line, such as {name: len(name) for name in names}. A set comprehension builds a set the same way.

Read List comprehension and Dictionaries first.

Build a dictionary from a list

Use curly brackets and write a key: value pair before the for.

names = ["Ada", "Ben", "Cyrus"]
lengths = {name: len(name) for name in names}
print(lengths)

Each name becomes a key, and its length becomes the value.

Loop over a dictionary with items()

items() hands over each key and value as a pair. Unpack the pair into two names after for.

prices = {"pen": 2, "book": 12, "bag": 30}
sale = {item: price // 2 for item, price in prices.items()}
print(sale)

The keys stay the same. Every price is halved in the new dictionary.

Filter a dictionary

Add if at the end to keep only some pairs.

scores = {"Ada": 18, "Ben": 9, "Cy": 14}
passed = {name: score for name, score in scores.items() if score >= 10}
print(passed)

"Ben" scored 9, so his pair is left out.

Build a dictionary from two lists with zip()

zip() pairs up the items of two lists by position. Each pair becomes one key and one value.

players = ["Ada", "Ben", "Cy"]
points = [12, 7, 15]
table = {player: score for player, score in zip(players, points)}
print(table)

The first player gets the first score, and so on. dict(zip(players, points)) gives the same result when you don't need to change anything.

Set comprehension

Leave out the colon and write one value. Curly brackets with one value make a set, which drops duplicates.

rolls = [3, 6, 3, 1, 6, 6]
unique = {roll for roll in rolls}
print(unique)

words = ["Cat", "dog", "CAT", "Dog"]
print(len({word.lower() for word in words}))

Only 1, 3 and 6 are left. The four words shrink to two once they are in lowercase.

Note: {} on its own makes an empty dictionary, not an empty set. Use set() for an empty set. A set has no fixed order, so sort a set of strings with sorted() before you print it.

See also: Sets and tuples, Unpacking, Nested data.

Your turn

Build a new dictionary with each price in cents (the price times 100), then print it.

prices = {"apple": 2, "melon": 5, "kiwi": 1}
# add two lines: build the dictionary with a comprehension, then print it

Expected output

{'apple': 200, 'melon': 500, 'kiwi': 100}

Practise this in the free Python course, where every exercise checks your code instantly.