Skip to main content
eLearner.app
Module 6 · Lesson 2 of 422/36 in the course~10 min
Module lessons (2/4)

Dict and set comprehension

The same syntax used for list comprehensions also works to build dict and set values — you just change the brackets.

Dict comprehension

Syntax: {key: value for element in iterable}.

Python
quadrati = {n: n * n for n in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Common pattern: turn a list of tuples into a dict.

Python
coppie = [("a", 1), ("b", 2), ("c", 3)]
d = {k: v for k, v in coppie}
# {'a': 1, 'b': 2, 'c': 3}
# (equivalente a dict(coppie) in questo caso)

Swap keys and values of a dict:

Python
originale = {"a": 1, "b": 2, "c": 3}
invertito = {v: k for k, v in originale.items()}
# {1: 'a', 2: 'b', 3: 'c'}

Filter a dict:

Python
prezzi = {"mela": 1.2, "pera": 1.5, "kiwi": 2.5, "ananas": 4.0}
economici = {k: v for k, v in prezzi.items() if v < 2.0}
# {'mela': 1.2, 'pera': 1.5}

Set comprehension

Syntax: {expression for element in iterable}. Same as a list comprehension, but with curly braces.

Python
parole = ["ciao", "mondo", "ciao", "python"]
uniche = {p.upper() for p in parole}
# {'CIAO', 'MONDO', 'PYTHON'}

Unique initials from a list of names:

Python
nomi = ["Ada", "Linus", "Grace", "Alan", "Guido"]
iniziali = {n[0] for n in nomi}
# {'A', 'L', 'G'}

Filter + transformation

As with list comprehensions, the trailing if filters:

Python
{n: n * n for n in range(10) if n % 2 == 0}
# {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}

Dict comprehensions for swapping keys and values

A very common pattern to invert a dictionary (swapping keys and values, assuming values are unique) is:

Python
orig_dict = {'a': 1, 'b': 2}
inv_dict = {value: key for key, value in orig_dict.items()}
# result: {1: 'a', 2: 'b'}

Try it

Exercise#python.m6.l2.e1
Attempts: 0Loading…

Given `words = ['mela', 'pera', 'kiwi', 'banana']`, build `lengths` as a dict {word: len(word)}. Evaluate `lengths`.

Loading editor…
Show hint

{p: len(p) for p in words}

Solution available after 3 attempts

Review exercise

Exercise#python.m6.l2.e2
Attempts: 0Loading…

Given `nums = [1, 2, 2, 3, 4, 4, 5]`, build `unique_squares` as a SET of the squares. Evaluate `unique_squares`.

Loading editor…
Show hint

Curly braces without ':' = set comprehension.

Solution available after 3 attempts

Additional challenge

Exercise#python.m6.l2.e3
Attempts: 0Loading…

Given the list of strings `names = ["Alice", "Bob"]`, use a dict comprehension to create a dictionary that maps each name to its length. Store the dictionary in `name_lengths` and evaluate it.

Loading editor…
Show hint

The syntax is {name: len(name) for name in names}.

Solution available after 3 attempts