The same idea of list comprehensions works to create dictionaries and sets, by changing the brackets to braces.
Dictionary comprehension
It is written {key: value for variable in collection}:
words = ["sun", "sea", "star"]
lengths = {w: len(w) for w in words}
print(lengths) # {'sun': 3, 'sea': 3, 'star': 4}
squares = {n: n ** 2 for n in range(1, 5)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16}
It is equivalent to this much longer loop:
lengths = {}
for w in words:
lengths[w] = len(w)
With a filter
grades = {"ana": 9, "luis": 4, "eva": 7}
passed = {name: grade for name, grade in grades.items() if grade >= 5}
print(passed) # {'ana': 9, 'eva': 7}
Inverting a dictionary
es_en = {"hola": "hello", "gato": "cat"}
en_es = {en: es for es, en in es_en.items()}
print(en_es) # {'hello': 'hola', 'cat': 'gato'}
If a key is repeated
If the comprehension generates the same key several times, it keeps the last value, and the key appears only once:
d = {w: len(w) for w in ["sun", "sea", "sun"]}
print(d) # {'sun': 3, 'sea': 3}
Set comprehension
With braces and without key:value pairs you get a set, which automatically removes repeated values:
words = ["Sun", "sun", "SEA", "sea", "star"]
unique = {w.lower() for w in words}
print(sorted(unique)) # ['sea', 'star', 'sun']
lengths = {len(w) for w in words}
print(sorted(lengths)) # [3, 4]
Summary of the four forms
| Result | Syntax |
|---|---|
| List | [x for x in data] |
| Dictionary | {k: v for k, v in pairs} |
| Set | {x for x in data} |
| Tuple | tuple(x for x in data) |
There is no comprehension of its own to create a tuple: parentheses create a generator expression, so it is converted with tuple().
Practice in Dictionary of lengths.