Dictionaries and dict.get()

Cerca i valori tramite chiave. get() restituisce un valore predefinito invece di un errore quando la chiave manca.

Sintassi

stats = {"hp": 20}
stats["hp"]
stats.get("battery", 0)
  • Assegnare un valore a una nuova chiave la aggiunge.

Esempio

stats = {"hp": 20}
print(stats["hp"])
print(stats.get("battery", 0))

Output:

20
0

Errori comuni

  • stats["missing"] solleva un KeyError. Usa get() quando la chiave potrebbe mancare.

Esercitati