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}.
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.
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:
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:
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.
parole = ["ciao", "mondo", "ciao", "python"]
uniche = {p.upper() for p in parole}
# {'CIAO', 'MONDO', 'PYTHON'}Unique initials from a list of names:
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:
{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:
orig_dict = {'a': 1, 'b': 2}
inv_dict = {value: key for key, value in orig_dict.items()}
# result: {1: 'a', 2: 'b'}Try it
Given `words = ['mela', 'pera', 'kiwi', 'banana']`, build `lengths` as a dict {word: len(word)}. Evaluate `lengths`.
Show hint
{p: len(p) for p in words}
Solution available after 3 attempts
Review exercise
Given `nums = [1, 2, 2, 3, 4, 4, 5]`, build `unique_squares` as a SET of the squares. Evaluate `unique_squares`.
Show hint
Curly braces without ':' = set comprehension.
Solution available after 3 attempts
Additional challenge
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.
Show hint
The syntax is {name: len(name) for name in names}.
Solution available after 3 attempts