Skip to content
Justice Tech School

Dictionary and Set Comprehensions

The same idea builds dictionaries and sets. {k: v for ...} creates a dict and {x for ...} creates a set. They are great for inverting a mapping, counting or removing duplicates.

Example
words = ["apple", "fig", "banana"]
lengths = {w: len(w) for w in words}
print(lengths)
flipped = {v: k for k, v in lengths.items()}
print(flipped)
first_letters = {w[0] for w in words}
print(sorted(first_letters))

Result

{'apple': 5, 'fig': 3, 'banana': 6}
{5: 'apple', 3: 'fig', 6: 'banana'}
['a', 'b', 'f']

Exercise

Build a dictionary comprehension.

{w: len(w)  w in words}

Quiz Test

What does {x for x in [1, 1, 2]} create?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.