Skip to main content
eLearner.app
Module 3 · Lesson 3 of 411/36 in the course~12 min
Module lessons (3/4)

Dictionaries

A dictionary (dict) is a key → value map: you associate a key (almost always a string) with a value of any type. It is the fundamental data structure for modeling real-world entities.

Creating a dictionary

Python
vuoto = {}
utente = {"nome": "Ada", "anni": 36, "attivo": True}
# costruttore alternativo
utente = dict(nome="Ada", anni=36, attivo=True)

Keys must be hashable (immutable): strings, numbers, tuples of hashable elements. Values, on the other hand, can be anything — even other dicts.

Access, modify, delete

Python
utente["nome"]            # 'Ada'
utente["email"]           # KeyError!
utente.get("email")       # None       (default sicuro)
utente.get("email", "—")  # '—'        (default custom)
utente["citta"] = "Roma"  # aggiunge / aggiorna
del utente["attivo"]      # rimuove

Iterating over a dict

Python
for chiave in utente:               # itera sulle CHIAVI (default)
    print(chiave, utente[chiave])

for chiave in utente.keys():        # esplicito
    ...

for valore in utente.values():
    print(valore)

for chiave, valore in utente.items():    # idiom più comune
    print(f"{chiave} = {valore}")

The iteration order is the insertion order (guaranteed since Python 3.7 onwards).

Does the key exist?

Python
"nome" in utente     # True
"email" in utente    # False     (NON usa il valore, usa la chiave!)

setdefault: initialize on first access

A frequent pattern: "if the key does not exist, put the default in; in any case return the current value".

Python
gruppi = {}
for nome in ["Ada", "Linus", "Ada", "Grace", "Linus", "Ada"]:
    gruppi.setdefault(nome, []).append(1)
# {'Ada': [1, 1, 1], 'Linus': [1, 1], 'Grace': [1]}

There is also collections.Counter for the specific case of counting (we will see it in the stdlib module).

Iterating over dictionaries

You can iterate over a dictionary in multiple ways:

  • for k in d: loops over keys only (default behavior).
  • for k, v in d.items(): loops over key-value pairs simultaneously (highly useful).
  • for v in d.values(): loops over values only.

Try it

Exercise#python.m3.l3.e1
Attempts: 0Loading…

Given `user = {'nome': 'Ada', 'anni': 36}`, add the key 'email' = 'ada@ex.com' and then assign to `email_or_default` the value of the key 'telefono' using .get with default 'sconosciuto'. Evaluate `email_or_default`.

Loading editor…
Show hint

.get('telefono', 'sconosciuto') does not raise KeyError.

Solution available after 3 attempts

Review exercise

Exercise#python.m3.l3.e2
Attempts: 0Loading…

Given `prices = {'mela': 1.2, 'pera': 1.5, 'kiwi': 2.0}`, compute the sum of all values and assign it to `total`. Evaluate `total`.

Loading editor…
Show hint

sum(prices.values()) adds up all the values.

Solution available after 3 attempts

Additional challenge

Exercise#python.m3.l3.e3
Attempts: 0Loading…

Given the dictionary `user = {'name': 'Alice'}`, use the `.get()` method to retrieve the value of the key `'role'`. If the key does not exist, make it return the default value `'guest'`. Store the result in `user_role` and evaluate it.

Loading editor…
Show hint

The get method accepts a second parameter as a fallback: user.get('role', 'guest').

Solution available after 3 attempts