Legends ofPythos
Claim your name
Working with Data

Dictionary and set comprehensions

Lesson 8 of 14

Watch the lesson1:11 · with Torsten

Dictionary and set comprehensions

You already build lists with [expr for item in iterable]. Python lets you swap that square bracket pair for curly braces to create dictionaries and sets directly. This removes the boilerplate for loop, keeping your logic in a single readable expression while still giving you full control over what goes into each new container.

Dictionary comprehensions

users = ['alice', 'bob', 'carol']
scores = {name: len(name) * 10 for name in users}
print(scores)
Map usernames to their profile completion scores.
The syntax is {key_expr : value_expr for item in iterable}. Each pass through the loop creates one key-value pair and drops it into the new dictionary. This example did three things at once: iterated over names, calculated a score based on name length, and stored each result under its username.
all_users = {'alice': 30, 'bob': 15, 'carol': 40}
veterans = {name: score for name, score in all_users.items() if score >= 20}
print(veterans)
Filter out users with scores below 20.
You can add an if clause at the end to skip items you do not want. This filtered out Bob because his score of 15 fell below your threshold.

Set comprehensions

sentence = ['the', 'quick', 'brown', 'fox']
unique_lengths = {len(word) for word in sentence}
print(unique_lengths)
Find unique word lengths from a sentence.
A set comprehension uses curly braces but no colon. Because sets only store unique values, duplicates vanish automatically. This collected the lengths 3 and 5 into a single unordered collection, ignoring that 'the' and 'fox' both have length 3.

Inverting dictionaries

temps = {'morning': 12, 'noon': 25, 'evening': 18}
inverted = {value: key for key, value in temps.items()}
print(inverted)
Swap keys and values for temperature readings.
You iterate over .items() to unpack both sides of each pair, then place the old value as the new key. This let you look up which time-of-day produced a specific temperature.
You now have a direct way to transform collections without temporary variables or multi-line loops. Use these comprehensions when you need to reshape data for display, filtering, or lookup tables; they keep your code tight and your intent obvious at a glance.

Your turn

0 of 2 solved

Exercise 1

+30 XP
Given word_lengths, build a dictionary called by_length that maps each word length to a set of the words that have that length. Use a dictionary comprehension with a set comprehension inside it.
word_lengths = {"hi": 2, "hey": 3, "ho": 2, "hello": 5}

Run your code to check it against the tests.

Exercise 2

+30 XP
Write a function filter_dict(d, min_val) that returns a new dictionary containing only the key-value pairs where the value is greater than or equal to min_val. Use only a single dict comprehension.
def filter_dict(d, min_val):
    pass

Run your code to check it against the tests.