Salt la conținutul principal
eLearner.app
Modulul 6 · Lecția 2 din 422/36 în curs~10 min
Lecții din modul (2/4)

Dictați și setați înțelegerea

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

Exercițiu#python.m6.l2.e1
Încercări: 0Se încarcă…

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

Se încarcă editorul...
Afișează indiciu

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

Soluție disponibilă după 3 încercări

Review exercise

Exercițiu#python.m6.l2.e2
Încercări: 0Se încarcă…

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

Se încarcă editorul...
Afișează indiciu

Curly braces without ':' = set comprehension.

Soluție disponibilă după 3 încercări

Additional challenge

Exercițiu#python.m6.l2.e3
Încercări: 0Se încarcă…

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.

Se încarcă editorul...
Afișează indiciu

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

Soluție disponibilă după 3 încercări