Python:字典
字典按键存放键值对,键必须可哈希,查找平均为常数时间并保留插入顺序。本文讲解下标、get 与 setdefault 的差别,以及更新与遍历的要点。
别名 · dict、映射
键、哈希与插入顺序 #
字典(dict)是键值映射,键必须可哈希(hashable):str、int 和元素都可哈希的元组可以,list、dict、set 不行。查找、插入、删除平均为常数时间。自 3.7 起字典保留插入顺序(insertion order),遍历顺序就是写入顺序,更新已有键不会改变位置。
scores = {"alice": 90, "bob": 85}
scores["alice"] = 95 # 更新已有键,位置不变
scores["carol"] = 78
print(list(scores), list(scores.items()))
try:
scores[["x"]] = 0
except TypeError:
print("列表不能作键")
输出第一行是 ['alice', 'bob', 'carol'],顺序与写入顺序一致。键的集合本身不重复,相关操作可参考集合。
读取:下标、get 与 setdefault #
d[key] 在键缺失时抛 KeyError,适合“键一定存在”的场合。get(key, default) 只返回默认值,不会修改字典;setdefault(key, default) 在缺失时插入默认值再返回,适合分组。in 只检查键,不检查值。
counts = {}
for word in "the cat and the hat".split():
counts[word] = counts.get(word, 0) + 1
print(counts, counts.get("dog", 0))
events = [("alice", "login"), ("bob", "login"), ("alice", "logout")]
by_user = {}
for user, action in events:
by_user.setdefault(user, []).append(action)
print(by_user)
更新、删除与合并 #
赋值插入或覆盖,update() 批量合并,pop(key) 删除并返回值,popitem() 弹出最后插入的项,del 按键删除。| 合并两个字典,右侧优先,|= 就地更新。需要按键排序输出时,用 sorted(d.items()) 而不是指望字典顺序。
config = {"host": "localhost", "port": 8080}
config.update({"port": 9000, "debug": True})
print(config)
print(config.pop("debug"), "debug" in config)
print({"a": 1} | {"b": 2, "a": 3})
print(config.popitem())
遍历与修改 #
keys()、values()、items() 返回视图(view),会随字典变化。遍历过程中插入或删除元素会破坏迭代器,运行时抛 RuntimeError: dictionary changed size during iteration;要修改就先复制键,写成 for key in list(d)。JSON 对象的读写与字典直接对应,见JSON 处理。
ages = {"alice": 30, "bob": 25, "carol": 35}
for name in list(ages):
if ages[name] < 30:
del ages[name]
print(ages, list(ages))
由已有数据构造字典时,字典推导式比循环赋值更紧凑,见推导式。