Python学习笔记:字典

封面

字典

定义:能够成队储存元素的序列

格式:字典名 = {key1:value1,key2:value2,……}

特性:每个键(key)都有一个与之关联的值(value)

创建字典

方法一:

1
2
# 通过直接赋值的方式创建一个字典
sport = {"John":"soccer","Mike":"volleyball","Bob":"baseball","Amy":"ping-pong"}

方法二:

1
2
3
4
5
6
# 创建一个空的字典,然后为其赋值
sport = {}
sport["John"] = "soccer"
sport["Mike"] = "volleyball"
sport["Bob"] = "baseball"
sport["Amy"] = "ping-pong"

查找字典元素

1
2
3
4
5
6
7
scores = {"语文":88, "数学":90, "英语":85,
"物理":87, "化学":75, "政治":93,
"地理":88, "生物":98, "历史":100,
"体育":87, "音乐":88, "美术":69}
print("我的化学成绩:", scores["化学"])
print("我的生物成绩:", scores.get("生物"))
print("我的信息成绩:", scores.get("信息"))

直接根据key查找value:dict[key]

使用get函数查找:dict.get(key)

编辑字典元素

1
2
3
4
5
6
7
8
9
list_books = {"史记":"司马迁",
"红与黑":"司汤",
"悲惨世界":"雨果",
"西游记":"吴承恩",
"本草纲目":"李时珍"}
list_books["昆虫记"] = "法布尔"
list_books["水浒传"] = "施耐庵"
list_books["红与黑"] = "司汤达"
print(list_books)

反向查找字典元素

1
2
3
4
5
6
7
8
9
10
id_name = {"01001":"小张",
"01005":"小王",
"01008":"小林",
"01015":"小李",
"01020":"小孔",
"01035":"小何"}
name_id = {}
for id,name in id_name.items():
name_id[name] = id
print("小李的学号:",name_id["小李"])

End