Set and dictionary comprehensions
🌍 In real life. A teacher asks: "Which first letters do your names start with?" She only wants each letter once: that's a set. Then: "Write each name with its length", one entry per name: that's a dictionary. The same quick recipe works for both.
The idea in one sentence: with curly braces, a comprehension builds a set ({expression for ...}) or, with key: value at the front, a dictionary ({key: value for ...}).
Its words:
- set comprehension:
{w[0] for w in words}; repeats are dropped - dict comprehension:
{w: len(w) for w in words}; one key per item, a later key overwriting an earlier one .items()in a comprehension: loop over another dictionary's pairs
Step by step, for {w: len(w) for w in ["fig", "kiwi"]}:
- w is "fig": add the pair
"fig": 3. - w is "kiwi": add
"kiwi": 4. - The result is
{'fig': 3, 'kiwi': 4}.
words = ["ant", "bee", "ape"]
firsts = {w[0] for w in words}
print(sorted(firsts))Write key: value at the front and you get a dictionary: {key: value for name in source}.
words = ["fig", "kiwi", "plum"]
lengths = {w: len(w) for w in words}
print(lengths)
squares = {n: n * n for n in range(1, 4)}
print(squares)A dictionary comprehension can loop over another dictionary's items(), unpacking each pair, and can filter too:
prices = {"pen": 10, "book": 50, "gum": 5}
cheap = {item: p for item, p in prices.items() if p < 20}
print(cheap)
flipped = {p: item for item, p in prices.items()}
print(flipped)How Python tells them apart. Square brackets make a list. Curly braces make a set, unless the expression has a colon, key: value, which makes a dictionary. Each one costs one lap per source item, plus a quick hash lookup to drop repeats or place keys.
Mistakes and edge cases.
- Repeated keys. Flipping
{"pen": 10, "cup": 10}into{p: item ...}keeps only one of them: both want the key 10, and the later one wins. - {} isn't an empty set. Even from a comprehension, an empty result
{x for x in []}isset(), but writing{}yourself makes a dictionary. - A list where you wanted a set.
[n for n in nums]keeps repeats; use{n for n in nums}to count different values (see the bug question). - Expecting order from a set. Use
sorted(...)when you print one.
Quiz
What does this print?
print(sorted({x % 3 for x in range(7)}))What does this print?
print({w: len(w) for w in ["a", "bb"]})What does this print?
print({n: n * 10 for n in range(2)})What does
{x: 0 for x in names}make?- A dictionary
- A set
- A list
What does this print?
d = {"a": 1, "b": 2} print({v: k for k, v in d.items()})This should print how many different numbers there are, 2, but it prints 3. Which line has the mistake?
nums = [3, 1, 3] unique = [n for n in nums] print(len(unique))
Coding tasks
Ask for some words on one line. Print a dictionary where each word leads to its length.
Ask for some words on one line. Print the sorted list of the different word lengths.
Ask for a number
n, then fornsentences, one per line. Print the largest number of words found in any one sentence.