Dictionary Comprehensions

Comprehensions

Dictionary Comprehensions

In this tutorial, we'll build dictionaries from loops.

A dictionary comprehension builds a dictionary using a loop-like expression.

Normal loop:

names = ["Ada", "Grace", "Linus"]
name_lengths = {}

for name in names:
    name_lengths[name] = len(name)

Dictionary comprehension:

names = ["Ada", "Grace", "Linus"]
name_lengths = {name: len(name) for name in names}

Output:

{"Ada": 3, "Grace": 5, "Linus": 5}

The Shape

{key_expression: value_expression for item in collection}

You decide what the key should be and what the value should be.

Example: Squares

numbers = [1, 2, 3, 4]
squares = {number: number * number for number in numbers}

Output:

{1: 1, 2: 4, 3: 9, 4: 16}

Filtering

You can add an if condition:

scores = {"Ada": 95, "Ben": 42, "Cara": 77}
passing = {name: score for name, score in scores.items() if score >= 50}

Using items()

When looping over an existing dictionary, .items() gives you both the key and value:

for name, score in scores.items():
    print(name, score)

Dictionary comprehensions often use this pattern because they need both parts.

Practice

Create a dictionary comprehension that maps each word in a list to its uppercase version.