字典
- 6.1 一个简单的字典
- 6.2 使用字典
- 6.2.1 访问字典中的值
- 6.2.2 添加键值对
- 6.2.3 创建一个字典
- 6.2.4 修改字典中的值
- 6.2.5 删除键值对
- 6.2.6 由类似对象组成的字典
- 6.2.7 使用get()来访问值
- 6.3 遍历字典
- 6.3.1 遍历所有键值对
- 6.3.2 遍历字典中所有的键
- 6.3.3 按特定顺序遍历字典中的所有键
- 6.3.4 遍历字典中的所有值
- 6.4 嵌套
- 6.4.1 在列表中存放字典
- 6.4.2 在字典中存储列表
- 6.4.3 在字典中存储字典
6.1 一个简单的字典
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])
print('')
字典里的内容是由键-值对构成的
6.2 使用字典
字典中的信息是n个键值对
6.2.1 访问字典中的值
alien_0 = {'color': 'green', 'grade': 5}
print(alien_0['color'])
new_points = alien_0['grade']
print(f"You got {alien_0['grade']}.")
print(new_points)
print('')
访问字典中的值,一般指的是通过访问字典的键,
然后得到键对应的值
6.2.2 添加键值对
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
# 新增外星人的x坐标和y坐标信息
alien_0['x_positon'] = 0
alien_0['y_positon'] = 25
print(alien_0)
print('')
方法:字典名.['键名'] = 值
6.2.3 创建一个字典
alien_0 = {}
print(alien_0)
alien_0['color'] = 'red'
alien_0['points'] = '100'
print(alien_0)
print('')
6.2.4 修改字典中的值
alien_0 = {'color': 'green', 'points': 5}
print(f"The alien is {alien_0['color']}.")
alien_0['color'] = 'yellow'
print(f"The alien is now {alien_0['color']}.")
alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
print(f"Original x-position:{alien_0['x_position']}.")
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment = 2
else:
x_increment = 3
alien_0['x_position'] = alien_0['x_position'] + x_increment
print(f"Nex x-position: {alien_0['x_position']}")
print('')
修改字典中的值和修改列表中的值差不多,
只不过这里不是访问列表的索引了,而是访问字典中的键
6.2.5 删除键值对
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points']
print(alien_0)
print('')
使用del语句删除字典中的键:del 字典名.['键']
删除键时,键值对会一起消失
6.2.6 由类似对象组成的字典
favourite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
print("Sarah's favorite language is " +
favourite_languages['sarah'].title() +
".")
language = favourite_languages['sarah'].title()
print(f"Sarah's favourite language is {language}.")
print('')
如果字典中的内容是类似对象,一般采用上述代码的书写风格创立字典
6.2.7 使用get()来访问值
people = {
'one': 'A',
'two': 'B',
'three': 'C',
}
X = people['three']
print(X)
X = people.get('four', 'hahaha')
print(X)
print('')
get方法会去寻找字典中的值,其中有两个参数:
第一个参数是要访问的键,第二个参数是没找到时要打印的语句。
如果字典中没有get方法中要求访问的键,那么会打印第二个参数。
6.3 遍历字典
6.3.1 遍历所有键值对
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key, value in user_0.items():
print(f"Key: {key}") # print("\nKey: " + a)
print(f"Value: {value}\n") # print("\nValue: " + b)
favourite_language = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name, language in favourite_language.items():
print(f"{name.title()} favorite language is {language.title()}.")
print()
字典的循环遍历和列表的不同之处在于,字典包括键值对,
所以要通过两个变量来循环遍历,
**遍历字典时用items方法,这个方法会返回一个键值对列表。**
6.3.2 遍历字典中所有的键
favourite_language = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in favourite_language.keys():
print(name.title())
print()
favourite_language = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
friends = ['phil', 'sarah']
for name in favourite_language.keys():
print(f"Hi {name.title()}.")
if name in friends:
language = favourite_language[name].title()
print(f"\t{name.title()}, I see you love {language}!")
if 'erin' not in favourite_language.keys():
print("Erin, please take you poll!")
print()
遍历键时要用到keys方法。
6.3.3 按特定顺序遍历字典中的所有键
这里我们使用函数sorted对列表、字典进行临时排序
favourite_language = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in favourite_language.keys():
print(f"{name.title()}, thank you for the poll.")
for name in sorted(favourite_language.keys()):
print(f"{name.title()}, thank you for the poll.")
print()
# 6.3.4 遍历字典中的所有值
favourite_language = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
print("The following languages have been mentioned:")
for language in set(favourite_language.values()):
print(language.title())
6.3.4 遍历字典中的所有值
favourite_language = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
print("The following languages have been mentioned:")
for language in set(favourite_language.values()):
print(language.title())
遍历字典中的值,和遍历键要用到方法keys一样,我们要用到方法values
6.4 嵌套
6.4.1 在列表中存放字典
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 6}
alien_2 = {'color': 'red', 'points': 7}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien)
aliens = []
for alien_number in range(30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)
for alien in aliens[:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
elif alien['color'] == 'yellow':
alien['color'] = 'red'
alien['speed'] = 'fast'
alien['points'] = 15
for alien in aliens[:5]:
print(alien)
print("...")
print("Total number of aliens:" + str(len(aliens)))
这里我们首先列举了一个简单的例子:
先定义字典,然后定义一个列表并存入先前定义的字典,
有的时候字典列表并不会只包含几个字典,而是n个,
所以我们要用到循环语句来在列表中添加字典,
for alien_number in range(30):
这个语句中,range(30)的意思是:要重复执行这个循环体30次
6.4.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)
favourite_languages = {
'jen': ['python', 'ruby'],
'sarah': ['c'],
'edward': ['ruby', 'go'],
'phil': ['python', 'haskell'],
}
for name, languages in favourite_languages.items():
print("\n" + name.title() + "favourite languages are:")
for language in languages:
print("\t" + language.title())
这里有一点需要注意:
我们在循环遍历存有列表的字典时,需要三个变量
首先,前两个变量用来循环遍历键值对,第三个变量用来循环遍历是列表的值。
以上解释其实不严谨,这里再进行充分得解释:
遍历字典,我们必须要有两个变量来进行循环,因为字典包含了键值对,
剩下的变量个数为n,因为你不知道有多少个值的形式其实是列表,因为只要是列表,我们就要另设一个变量来循环遍历该列表
6.4.3 在字典中存储字典
users = {
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'mucrie': {
'first': 'marie',
'last': 'curie',
'location': 'paris',
},
}
for username, user_info in users.items():
print(f"\nUsername:{username}")
full_name = f"{user_info['first']}{user_info['last']}"
location = user_info['location']
print(f"\tFull name:{full_name.title()}")
print(f"\tLocation:{location.title()}")
在字典中存储字典,可以理解为套娃,
我们要循环遍历并打印字典中的字典的值,首先要用到两个变量遍历最外层字典,
举个例子:我们用A、B循环遍历字典中的字典。B遍历的是字典中的字典,
我们如果要取得B中的值,那么必须要通过访问B中的键,来获得相对应的值。