第6章 字典
在本章中,你将学习能够将相关信息关联起来的python字典。
6.1 一个简单的字典
alien_0 = {'color': "green", 'points': 5}
print(alien_0)
print(alien_0['color'])
{'color': 'green', 'points': 5}
green
6.2 使用字典
在python中,字典是一系列的键-值对。每个键都与一个值相关联,可以用键访问与之相关联的值。
与键相关联的值可以是数字、字符串、列表乃至字典。
字典用放在花括号中的一系列键值对表示。1、访问字典中的值。指出字典名和键。
2、添加键-值对。指出字典名以及键值对。
3、修改字典中的值。可依次指定字典名、用方括号括起来的键以及与该键相关联的新值。
4、删除键值对。del 字典名[键]
print(alien_0)
alien_0['height'] = 2
print(alien_0)
alien_0['points'] = 10
print(alien_0)
del alien_0['height']
print(alien_0)
{'color': 'green', 'points': 5}
{'color': 'green', 'points': 5, 'height': 2}
{'color': 'green', 'points': 10, 'height': 2}
{'color': 'green', 'points': 10}
6.3 遍历字典
1、遍历所有的键值对。字典名.items()
2、遍历字典中所有的键。字典名.keys()
3、遍历字典中所有的值。字典名.values()
print(alien_0)
for key, value in alien_0.items():
print(key, value)
for key in alien_0.keys():
print("The key is : " + key)
for value in alien_0.values():
print("The value is : " + str(value))
{'color': 'green', 'points': 10}
color green
points 10
The key is : color
The key is : points
The value is : green
The value is : 10
6.4 嵌套
有时需要将字典存储在列表中,或是将列表存储早字典中,这称为嵌套。
在列表中嵌套字典、在字典中嵌套列表甚至在字典中嵌套字典。
1、字典列表。列表中嵌套字典。
2、在字典中存储列表。
3、在字典中存储字典
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
print(aliens)
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)
print(aliens)
[{'color': 'green', 'points': 10}, {'color': 'yellow', 'points': 10}, {'color': 'red', 'points': 15}]
[{'color': 'green', 'points': 10}, {'color': 'yellow', 'points': 10}, {'color': 'red', 'points': 15}, {'color': 'green', 'points': 5, 'speed': 'slow'}]
pizza = {'crust': 'thick', 'toppings': ['mushroom', 'extra cheeses']}
print("You ordered a " + pizza['crust'] + "with the following toppings : ")
for topping in pizza['toppings']:
print(topping)
You ordered a thickwith the following toppings :
mushroom
extra cheeses
user = {
'aeinstein':{
'firstname': 'albert',
'lastname': 'einstein',
'location': 'princeton'
},
'mcurie':{
'firstname': 'marie',
'lastname': 'curie',
'location': 'paris'
},
}
for user_name, user_info in user.items():
print("User name is : " + user_name)
for key, value in user_info.items():
print(key + " : " + value)
User name is : aeinstein
firstname : albert
lastname : einstein
location : princeton
User name is : mcurie
firstname : marie
lastname : curie
location : paris
练习
1、使用一个字典存储一个熟人的信息,包括名、姓、年龄以及居住的城市。将存储在该字典中的每项信息都打印出来。
2、宠物:创建多个字典,对于每个字典都用一个宠物的名称来给它命名;在每个字典中包含宠物的类型以及其主人的名字。将这些字典存储在一个名为pets的列表中,再遍历该列表,将宠物的所有信息都打印出来。
3、城市:创建一个名为cities的字典,其中将3个城市名用作键;对于每个城市都创建一个字典,并在其中包含该城市所属的国家、人口约数以及一个有关该城市的事实。即在每个城市的字典中应包含country、population和facts键。将每个城市的名字以及其有关的信息都打印出来。
增删查改!