4.5 字典
字典(dictionary)保存的是键值对(key-value pair),也就是 key -> value 的映射(mapping)。key 必须唯一,value 可以重复。
创建与访问
字典使用 {} 或 dict() 创建。访问 value 时,不使用数字下标,而是使用 key。
python
info = {"name": "Alice", "age": 24, "height": 179.2}
print(info["name"]) # Alice
print(info["age"]) # 24如果 key 不存在,直接使用 info[key] 会抛出 KeyError。如果不确定 key 是否存在,可以使用 get()。
python
print(info.get("age")) # 24
print(info.get("score")) # None正在加载概念检查...
遍历字典
直接遍历(iterate)字典时,得到的是 key。
python
info = {"name": "Alice", "age": 24, "height": 179.2}
for key in info:
print("键=%s,值=%s" % (key, info[key]))如果希望同时得到 key 和 value,可以使用 items()。
python
for key, value in info.items():
print("键=%s,值=%s" % (key, value))正在加载交互实验...
字典方法
常用字典方法包括:
keys():获取所有 key。values():获取所有 value。items():获取所有键值对。update():更新或添加键值对。get():按 key 获取 value。pop():按 key 删除键值对。clear():清空字典。
python
info = {"name": "Alice"}
print("信息 =", info)
info.update({"age": 24, "height": 179.2})
print("更新后 =", info)
print("所有键 =", info.keys())
print("所有值 =", info.values())
print("年龄 =", info.get("age"))
info.pop("height")
print("删除身高后 =", info)词频统计
字典很适合做计数器。下面的程序统计每个单词出现了多少次。
注意
string 是 Python 标准库中的模块。这里第一次使用它,是为了借用 string.punctuation:它保存了常见标点符号,方便用 strip() 去掉单词两端的标点。python
import string
text = "Python is simple. Python is powerful."
words = text.split()
frequency = {}
for word in words:
word = word.lower().strip(string.punctuation)
if word not in frequency:
frequency[word] = 1
else:
frequency[word] += 1
for word, count in frequency.items():
print("%s: %d" % (word, count))运行结果:
text
python: 2
is: 2
simple: 1
powerful: 1正在加载概念检查...
正在加载本节练习...