首页 › Python 数据结构 › 字典 dict

字典 dict

字典保存"键: 值"对,通过键快速查找值。

student = {"name": "小红", "age": 19, "major": "计算机"}
print(student["name"])
student["age"] = 20            # 修改
student["city"] = "杭州"        # 新增
del student["major"]           # 删除

安全读取

直接用 [] 访问不存在的键会抛出 KeyError,用 get() 更安全:

print(student.get("phone"))          # None
print(student.get("phone", "未填写"))  # 未填写

遍历

for key, value in student.items():
    print(key, "=>", value)

keys()、values()、items() 分别返回键、值、键值对。

统计示例

text = "the cat and the hat"
count = {}
for word in text.split():
    count[word] = count.get(word, 0) + 1
print(count)   # {'the': 2, 'cat': 1, 'and': 1, 'hat': 1}

字典的键必须是不可变类型(字符串、数字、元组),从 Python 3.7 开始字典会保持插入顺序。

练习题

学完本节后,试着独立完成下面的练习,再展开参考答案对照。

练习 1 统计句子 "to be or not to be" 中每个单词出现的次数(不用 Counter)。

查看参考答案
count = {}
for w in "to be or not to be".split():
    count[w] = count.get(w, 0) + 1
print(count)
参考输出:
{'to': 2, 'be': 2, 'or': 1, 'not': 1}

练习 2 把字典 {"a": 1, "b": 2, "c": 1} 的键值对调,值相同的键放进同一个列表。

查看参考答案
d = {"a": 1, "b": 2, "c": 1}
inv = {}
for k, v in d.items():
    inv.setdefault(v, []).append(k)
print(inv)
参考输出:
{1: ['a', 'c'], 2: ['b']}