Lesson 2 of 16 · Pythonic Code
Dictionary and Set Comprehensions
Build dictionaries and sets in one line with comprehensions. Learn to transform, filter and invert dictionaries, and remove duplicates with set comprehensions.
- 7 min read
- Intermediate
- Reviewed
- How to build a dictionary with a comprehension
- How to transform and filter an existing dictionary
- How to build a set of unique values
- How to tell the different comprehension brackets apart
From lists to dictionaries
A list comprehension uses square brackets. Swap them for curly brackets and write key: value at the front, and you get a dictionary comprehension.
words = ["data", "model", "training"]
lengths = {word: len(word) for word in words}
print(lengths)For every word, the comprehension creates one entry: the word is the key and its length is the value.
Building a dictionary from two lists
zip() pairs up items from two lists. It fits naturally into a dictionary comprehension.
names = ["Ada", "Grace", "Alan"]
scores = [92, 85, 78]
results = {name: score for name, score in zip(names, scores)}
print(results)
print(results["Grace"])Transforming a dictionary
Loop over .items() to work with both the key and the value.
prices = {"apple": 30, "banana": 10, "cherry": 120}
discounted = {item: price * 0.9 for item, price in prices.items()}
print(discounted)Filtering a dictionary
Add if at the end, exactly as in a list comprehension.
stock = {"apples": 8, "pears": 0, "kiwis": 10, "plums": 0}
available = {item: count for item, count in stock.items() if count > 0}
print(available)Swapping keys and values
Sometimes you need to look things up the other way round. Swap the key and the value.
codes = {"IN": "India", "JP": "Japan", "BR": "Brazil"}
by_name = {country: code for code, country in codes.items()}
print(by_name)
print(by_name["Japan"])This only works well if every value is unique. If two keys share a value, the later one wins and the other is lost.
Set comprehensions
Curly brackets without a colon build a set: a collection of unique values with no fixed order.
emails = ["[email protected]", "[email protected]", "[email protected]", "[email protected]"] domains = {email.split("@")[1] for email in emails} print(domains) print(len(domains))
Four emails, but only two different domains. A set keeps each value once, so duplicates disappear automatically. The order a set prints in may differ from run to run, so never rely on it.
To get a sorted list from a set, pass it to sorted():
tags = ["python", "AI", "Python", "ml", "ai", "ML"]
unique = sorted({tag.lower() for tag in tags})
print(unique)Which brackets make what?
| You write | You get |
|---|---|
[x for x in items] | a list |
{x for x in items} | a set |
{k: v for k, v in pairs} | a dictionary |
Round brackets, (x for x in items), make something different called a generator. You will meet generators in Advanced Python.
Common mistakes
Use a dictionary comprehension to keep only the students who passed.
marks = {"Ada": 92, "Grace": 58, "Alan": 78, "Linus": 45}
# Build a dictionary called passed with only the students who scored 60 or more.
# Each value should be "pass". Then print it. Output must be exactly:
# {'Ada': 'pass', 'Alan': 'pass'}
What does {len(w) for w in ['ai', 'ml', 'data']} produce?
Summary
{key: value for item in items}builds a dictionary.- Loop over
.items()to transform or filter an existing dictionary. {value for item in items}builds a set of unique values.- An empty set is
set(), because{}is an empty dictionary.
Next: unpacking, a neat way to pull values out of lists and tuples.
Finished reading? Tick it off to track your progress.