下面是关于Python3中dict(字典)的使用方法示例的攻略:
什么是Python3中的字典?
Python中的字典是一种无序的、可变的、可迭代的键值对集合。每个键都与一个唯一的值相对应。
创建一个字典
创建字典可以使用大括号{}或 dict()函数:
# 创建空字典
empty_dict = {}
# 或者
empty_dict_2 = dict()
# 创建有值的字典
person = {"name": "Lucy", "age": 18, "gender": "female"}
字典的基本操作
添加或修改字典项
可以通过使用字典的键来添加或修改字典项:
person = {"name": "Lucy", "age": 18, "gender": "female"}
# 修改已有的键值对
person["age"] = 19
# 添加新的键值对
person["city"] = "Shanghai"
删除字典项
使用del或pop()方法可以删除字典中的键值对:
person = {"name": "Lucy", "age": 18, "gender": "female"}
# 使用del删除键值对
del person["gender"]
# 使用pop()方法删除键值对
person.pop("age")
字典遍历
可以使用for循环迭代字典中的键或值:
person = {"name": "Lucy", "age": 18, "gender": "female"}
# 遍历所有键
for key in person:
print(key)
# 遍历所有值
for value in person.values():
print(value)
# 遍历所有键值对
for key, value in person.items():
print(key, ":", value)
示例1:使用字典记录学生的成绩信息
示例代码如下:
# 定义一个字典,存储学生的成绩信息
scores = {"Lucy": 90, "Bob": 80, "Tom": 95}
# 输出每个学生的成绩
for name, score in scores.items():
print(name, "的成绩是:", score)
# 添加一个新的学生
scores["Annie"] = 88
# 输出每个学生的成绩
for name, score in scores.items():
print(name, "的成绩是:", score)
运行结果如下:
Lucy 的成绩是: 90
Bob 的成绩是: 80
Tom 的成绩是: 95
Annie 的成绩是: 88
示例2:使用字典统计单词出现的次数
示例代码如下:
# 定义字符串
sentence = "I love Python, because it is so easy and powerful."
# 将字符串转换为列表
word_list = sentence.split()
# 定义一个字典,存储每个单词出现的次数
word_count = {}
# 遍历列表,统计每个单词出现的次数
for word in word_list:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# 输出统计结果
for word, count in word_count.items():
print(word, ":", count)
运行结果如下:
I : 1
love : 1
Python, : 1
because : 1
it : 1
is : 1
so : 1
easy : 1
and : 1
powerful. : 1