# Literal with braces
user = {"name": "Rosa", "age": 30, "city": "Lisbon"}
print(user)
# Empty dict, built up over time
counts = {}
counts["a"] = 1
counts["b"] = 2
print(counts)
# From a list of (key, value) pairs
pairs = [("one", 1), ("two", 2), ("three", 3)]
mapping = dict(pairs)
print(mapping)
# With keyword arguments
config = dict(host="localhost", port=8080, debug=True)
print(config)
读取值
有两种方法,选哪种很重要:
prices = {"apple": 0.50, "bread": 2.00}
# [] - direct indexing. KeyError if missing.
print(prices["apple"])
# .get() - returns None (or a default) if missing.
print(prices.get("milk")) # None
print(prices.get("milk", 0.00)) # 0.00
根据意图来选:
用 []:当这个键“必须”存在时。如果它不存在,那就是 bug,你希望程序大声报错。
用 .get():当“不存在”也是正常情况时。它让你不用 try/except 就能写出默认值。
添加、更新、删除
给一个键赋值,要么创建它,要么更新它:
prices = {"apple": 0.50, "bread": 2.00}
prices["milk"] = 1.20 # new key
prices["apple"] = 0.60 # existing key, overwritten
print(prices)
del prices["bread"] # remove a key; KeyError if missing
print(prices)
gone = prices.pop("apple") # remove and return; accepts a default
print("was:", gone, "now:", prices)
# pop with a default so it doesn't raise
prices.pop("missing", None)
user = {"name": "Rosa", "age": 30}
print("name" in user) # True
print("email" in user) # False
print("Rosa" in user) # False - that's a value, not a key
要专门检查值,请用 user.values():
print(30 in user.values())
如何遍历字典
你可以遍历三种视图:
scores = {"ada": 90, "rosa": 85, "malik": 78}
# Keys (the default)
for name in scores:
print(name)
# Values
for score in scores.values():
print(score)
# Both - the common case
for name, score in scores.items():
print(f"{name}: {score}")
counts = {}
for word in ["one", "two", "one", "three", "two", "one"]:
counts.setdefault(word, 0)
counts[word] += 1
print(counts)
或者,更好的做法是用 collections.Counter:
from collections import Counter
words = ["one", "two", "one", "three", "two", "one"]
print(Counter(words))
Counter 是字典的子类,默认就会计数。只要是统计出现次数,用它就对了。
字典推导式
和列表推导式类似,只不过是用来构建字典的:
numbers = [1, 2, 3, 4, 5]
squares = {n: n * n for n in numbers}
print(squares)
# Invert a dict (keys become values and vice versa)
prices = {"apple": 0.50, "bread": 2.00}
lookup = {v: k for k, v in prices.items()}
print(lookup)
规则和列表推导式一样,只是花括号里写的是 key: value。
字典是 JSON 的孪生兄弟
Python 字典和 JSON 对象几乎一一对应。在两者之间转换只需要一次调用:
import json
data = {"name": "Rosa", "age": 30, "tags": ["python", "docs"]}
as_json = json.dumps(data)
print(as_json)
back = json.loads(as_json)
print(back)
这就是字典在 Web 开发中随处可见的原因:你的 API 请求和响应,本质上就是在操作字典,中间隔着一层网络而已。