Learn Python · lesson 54 of 60 · about 8 minutes
Dictionary and Set Comprehensions
Build dictionaries and sets in one line, the same way as lists.
What you'll learn
- Build a dictionary with a comprehension
- Build a set with a comprehension
- Turn one dictionary into another
Film night
Friday in Sam's week plan is film night. Sam types who's coming, like ada bo Ada cy, and friends end up typed twice or in different cases. The assistant needs each friend once, in a neat capitalised form, and not Sam, then the snacks: one popcorn, two juices and three cookies a person, for the guests and Sam. A set comprehension gives the guests, and a dictionary comprehension turns the snacks for one person into snacks for everyone.
Curly brackets and a colon
A dictionary comprehension uses curly brackets and a key: value pair: {w: len(w) for w in words} maps each word to its length. You can still add if at the end to filter.
Words and their lengths
words = ["tea", "phoebe", "go"]
print({w: len(w) for w in words})
print({w: len(w) for w in words if len(w) > 2})Output
{'tea': 3, 'phoebe': 6, 'go': 2}
{'tea': 3, 'phoebe': 6}Sets, and changing a dictionary
Curly brackets without a colon make a set: {w[0] for w in words} collects the different first letters, with no repeats.
To change a dictionary, loop over .items(): {name: score + 5 for name, score in marks.items()}.
A set, and a changed dictionary
words = ["apple", "avocado", "banana"]
print(sorted({w[0] for w in words}))
marks = {"Ada": 70, "Bo": 55}
print({name: score + 5 for name, score in marks.items()})Output
['a', 'b']
{'Ada': 75, 'Bo': 60}Tidy first, then drop the repeats
In {g.title() for g in friends}, each name is tidied with .title() before it goes into the set, so ada and Ada both become Ada and the set keeps just one. An if at the end can leave someone out altogether: if g.lower() != name.lower() skips Sam however Sam's name was typed.
Tip
Sets don't keep any order, so wrap one in sorted() when you print it if you want the same output every time.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.