Sub topic 2
Building Dictionaries, Sets, and Flattened Data with Comprehensions
Assume you know Python for loops, range, lists, dictionaries, sets, boolean expressions, and methods such as append. Comprehensions provide a compact way to create a collection from an iterable.
Building dictionaries with dict comprehensions
A dictionary comprehension uses key: value before the for clause:
words = ["apple", "banana", "cherry"]
lengths = {word: len(word) for word in words}
print(lengths)
# {'apple': 5, 'banana': 6, 'cherry': 6}You can add a trailing if to filter items:
long_words = {word: len(word) for word in words if len(word) > 5}
print(long_words)
# {'banana': 6, 'cherry': 6}If multiple items produce the same key, the later value replaces the earlier value:
inverted = {length: word for word, length in lengths.items()}
print(inverted)
# {5: 'apple', 6: 'cherry'}Both "banana" and "cherry" have length 6, so "cherry" is retained.
Building sets with set comprehensions
A set comprehension uses braces with one expression, not a key: value pair:
words = ["apple", "banana", "cherry", "fig"]
unique_lengths = {len(word) for word in words}
print(unique_lengths)
# {3, 5, 6}Sets automatically discard duplicate values. Remember that {} creates an empty dictionary, so create an empty set with set().
Multiple `for` clauses and flattening nested data
Multiple for clauses correspond to nested loops. The outer iterable comes first:
matrix = [[1, 2, 3], [4, 5, 6]]
flat = [value for row in matrix for value in row]
print(flat)
# [1, 2, 3, 4, 5, 6]This is equivalent to:
flat = []
for row in matrix:
for value in row:
flat.append(value)You can filter combinations after both for clauses:
pairs = [(x, y) for x in range(3) for y in range(3) if x < y]
print(pairs)
# [(0, 1), (0, 2), (1, 2)]The order matters. Swapping the clauses changes which iterable is nested inside the other.
Exercise
What is the result of {n % 2 for n in range(6)}?
Show answer
{0, 1}, because the remainder values repeat and a set keeps each value only once.