跳转到主要内容
模块 3 · 第 3 课(共 4)课程中的11/36~12 min
模块课程(3/4)

词典

字典 (dict) 是一个 键→值 映射:您关联一个键 (几乎总是一个字符串)具有任何类型的值。这是根本 用于对现实世界实体进行建模的数据结构。

创建字典

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

键必须是可哈希(不可变):字符串、数字、可哈希元组 元素。另一方面,价值观可以是任何东西——甚至是其他的指令。

访问、修改、删除

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

迭代字典

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}")

迭代顺序是 插入 顺序(自 Python 3.7 起保证) 以后)。

钥匙存在吗?

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

setdefault:首次访问时初始化

常见模式:“如果键不存在,则将默认值放入;在任何 case 返回当前值”。

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]}

还有 collections.Counter 用于计数的具体情况(我们 将在 stdlib 模块中看到它)。

迭代字典

您可以通过多种方式迭代字典:

  • for k in d:仅循环键(默认行为)。
  • for k, v in d.items():同时循环键值对(非常有用)。
  • for v in d.values():仅循环值。

尝试一下

锻炼#python.m3.l3.e1
尝试:0加载中...

给定 `user = {'nome': 'Ada', 'anni': 36}`,添加键 'email' = 'ada@ex.com',然后使用默认值为 'sconosciuto' 的 .get 将键 'telefono' 的值分配给 `email_or_default`。评估“email_or_default”。

正在加载编辑器...
显示提示

.get('telefono', 'sconosciuto') 不会引发 KeyError。

3 次尝试后可用的解决方案

复习练习

锻炼#python.m3.l3.e2
尝试:0加载中...

给定 `prices = {'mela': 1.2, 'pera': 1.5, 'kiwi': 2.0}`,计算所有值的总和并将其分配给 `total`。评估“总计”。

正在加载编辑器...
显示提示

sum(prices.values()) 将所有值相加。

3 次尝试后可用的解决方案

额外的挑战

锻炼#python.m3.l3.e3
尝试:0加载中...

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.

正在加载编辑器...
显示提示

get 方法接受第二个参数作为后备:user.get('role', 'guest')。

3 次尝试后可用的解决方案