python3_字典
一.字典的增删改查
1.定义
在Python中,字典 是一系列键—值对。每个键都与一个值相关联,你可以使用键来访问与之相关联的值。与键相关联的值可以是数字、字符串、列表乃至字典。事实上,可将任何Python对象用作字典中的值。
#定义一个字典
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])
2.添加键 - 值对:
字典名 [‘key值’] = value值
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
#结果:
{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5, 'y_position': 25, 'x_position': 0}
3.修改字典中的值:
字典名 [‘key值’] = 新value值
alien_0 = {'color': 'green'}
print("The alien is " + alien_0['color'] + ".")
alien_0['color'] = 'yellow'
print("The alien is now " + alien_0['color'] + ".")
结果:
The alien is green.
The alien is now yellow.
4.删除键 - 值对:
对于字典中不再需要的信息,可使用del 语句将相应的键—值对彻底删除。使用del 语句时,必须指定字典名和要删除的键。
!!!删除的键—值对永远消失了。
del 字典名 [‘key值’] = value值
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points']
print(alien_0)
结果为:
{'color': 'green', 'points': 5}
{'color': 'green'}
5.字典可选用类似对象的格式
定义好字典后,在最后一个键—值对的下一行添加一个右花括号,并缩进四个空格,使其与字典中的键对齐。另外一种不错的做法是在最后一个键—值对后面也加上逗号,为以 后在下一行添加键—值对做好准备。
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
【练习】:
1 人 :使用一个字典来存储一个熟人的信息,包括名、姓、年龄和居住的城市。该字典应包含键first_name 、last_name 、age 和city 。将存储在该字典中 的每项信息都打印出来。
Xiaofang = {
'first_name': 'Han',
'last_name': 'Gao',
'sex': 'male',
'year': '18',
'city': 'Fuzhou'
}
for key, values in Xiaofang.items():
print(key + " : " + values)
2 喜欢的数字 :使用一个字典来存储一些人喜欢的数字。请想出5个人的名字,并将这些名字用作字典中的键;想出每个人喜欢的一个数字,并将这些数字作为值存 储在字典中。打印每个人的名字和喜欢的数字。为让这个程序更有趣,通过询问朋友确保数据是真实的。
dictory = {
'Xiaofang': '11',
'ZaZaYang': '8',
'ZaZaHui': '9'
}
for key, value in dictory.items():
print(key + "最喜欢的数字是:" + value)
3 词汇表 :Python字典可用于模拟现实生活中的字典,但为避免混淆,我们将后者称为词汇表。
- 想出你在前面学过的5个编程词汇,将它们用作词汇表中的键,并将它们的含义作为值存储在词汇表中。
- 以整洁的方式打印每个词汇及其含义。为此,你可以先打印词汇,在它后面加上一个冒号,再打印词汇的含义;也可在一行打印词汇,再使用换行符(\n )插 入一个空行,然后在下一行以缩进的方式打印词汇的含义。
dictionary = {
'word': '单词',
'appale': '苹果',
'mellon': '瓜',
'big older': '大佬'
}
dictionary['word'] = '句子'
# print(dictionary['word'])
for key, value in dictionary.items():
print(key + "的意思是:" + value)
二.遍历字典
1.遍历所有键 - 值对:
方法items() ,它返回一个键—值对列表
for 键,值 in 字典.items():
案例可见上文
2.遍历字典中的所有键:
方法keys() ,返回所有键
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in favorite_languages.keys():
print(name.title()
结果:
Jen
Sarah
Phil
Edward
2.2排序:
函数sorted() 来获得按特定顺序排列的键列表的副本:
默认按照字母排序
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in sorted(favorite_languages.keys()):
print(name.title() + ", thank you for taking the poll.")
结果为:
Edward, thank you for taking the poll.
Jen, thank you for taking the poll.
Phil, thank you for taking the poll.
Sarah, thank you for taking the poll.
3.遍历字典中的所有值:
方法values() ,它返回一个值列表,而不包含任何键。
方法类似返回键
【练习】:
5 河流 :创建一个字典,在其中存储三条大河流及其流经的国家。其中一个键—值对可能是’nile’: ‘egypt’ 。
- 使用循环为每条河流打印一条消息,如“The Nile runs through Egypt.”。
- 使用循环将该字典中每条河流的名字都打印出来。
- 使用循环将该字典包含的每个国家的名字都打印出来。
information = {
'Koren': 'a river',
'Japen': 'b river',
'China': 'Yellow River',
'egypt': 'nile'
}
for country, river in information.items():
print("The " + river + " runs through " + country)
三.嵌套
“嵌套”将一系列字典存储在列表中,或将列表作为值存储在字典中。
你可以在列表中嵌套字典、在字典中嵌套列表甚至在字典中嵌套字典。
1.列表嵌套字典
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
#列表:
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien)
答案:
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}
2.字典中嵌套列表
pizza = {
'crust': 'thick',
# 字典嵌套列表
'toppings': ['mushrooms','extra cheese'],
}
print("You ordered a " + pizza['crust'] + "-crust pizza " +
"with the following toppings:")
for topping in pizza['toppings']:
print("\t" + topping)
结果:
You ordered a thick-crust pizza with the following toppings:
mushrooms
extra cheese
3.字典中嵌套字典
users = {
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris',
},
}
【练习】:
7 人 :在为完成练习6-1而编写的程序中,再创建两个表示人的字典,然后将这三个字典都存储在一个名为people 的列表中。遍历这个列表,将其中每个人的所有 信息都打印出来。
Xiaofang = {
'first_name': 'Han',
'last_name': 'Gao',
'sex': 'male',
'year': '18',
'city': 'Fuzhou'
}
Xiaofang2 = {
'first_name': 'Han',
'last_name': 'Gao',
'sex': 'male',
'year': '18',
'city': 'Fuzhou'
}
Xiaofang3 = {
'first_name': 'Han',
'last_name': 'Gao',
'sex': 'male',
'year': '18',
'city': 'Fuzhou'
}
lists = [Xiaofang, Xiaofang2, Xiaofang3]
for list in lists:
print(list)
9 喜欢的地方 :创建一个名为favorite_places 的字典。在这个字典中,将三个人的名字用作键;对于其中的每个人,都存储他喜欢的1~3个地方。为让这个练 习更有趣些,可让一些朋友指出他们喜欢的几个地方。遍历这个字典,并将其中每个人的名字及其喜欢的地方打印出来。
favorite_places = {
'peter': ['a', 'b', 'c'],
'Pill': ['a', 'B', 'c'],
'Mak': ['A', 'B', 'c']
}
for name, places in favorite_places.items():
for place in places:
print(name + "喜欢的地方有:" + place)
结果为:
peter喜欢的地方有:a
peter喜欢的地方有:b
peter喜欢的地方有:c
Pill喜欢的地方有:a
Pill喜欢的地方有:B
Pill喜欢的地方有:c
Mak喜欢的地方有:A
Mak喜欢的地方有:B
Mak喜欢的地方有:c