将一系列字典存储再列表中,或将列表作为值存储再字典中,称为嵌套。
1.在列表中存储字典
#创建一个用于存储外星人的空列表
aliens = []
for alien_number in range(30):
new_alien = {'color': 'green', 'point': '5', 'speed': 'low'}
aliens.append(new_alien)
#显示前五个外星人
print(aliens[:5])
for alien in aliens[:5]:
print(alien)
#for循环中alien存储最新的一个值
result:
{'color': 'green', 'point': '5', 'speed': 'low'}
{'color': 'green', 'point': '5', 'speed': 'low'}
{'color': 'green', 'point': '5', 'speed': 'low'}
{'color': 'green', 'point': '5', 'speed': 'low'}
{'color': 'green', 'point': '5', 'speed': 'low'}
...
也可以修改字典中的成员,改变其值。
for alien in aliens[:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['point'] = '10'
alien['speed'] = 'medium'
elif alien['color'] == 'yellow':
alien['color'] = 'red'
alien['point'] = '15'
alien['speed'] = 'fast'
print(alien)
result:
{'color': 'yellow', 'point': '10', 'speed': 'medium'}
{'color': 'yellow', 'point': '10', 'speed': 'medium'}
{'color': 'yellow', 'point': '10', 'speed': 'medium'}
2.在字典中存储列表
式例1:
pizza = {
'crust': 'thick',
'toppings': ['mushroom', 'extra cheese'],
}
for topping in pizza['toppings']:
print("\t" + topping)
result:
mushroom
extra cheese
#for循环获取列表中每个元素,并调用print打印出来
示例2:
favorite_languages = {
'张三': ['python', 'c']
'李四': ['ruby', 'go']
'王二': ['java', 'php'],
}
for name, languages in favorite_languages.items():
print("\n" + name.title() + "`s favorite language are")
for language in languages:
print("\t" + language.title())
result :
张三`s favorite language are
Python
C
李四`s favorite language are
Ruby
Go
王二`s favorite language are
Java
Php
# name和languages变量内次存储一个值,外部for循环打印出键,
#内部for循环打印出键的值
#可以在遍历字典的for循环下添加
#if len(languages) == 1:
#判断喜欢的语言为1中的情况
3.在字典中存储字典
在字典中存储字典和在字典中存储列表,都是对“值“进行操作。将列表和字典放在字典”值“的位置。
示例1:
users = {
'爱因斯坦': {
'first':'阿尔伯特',
'last': '爱因斯坦',
'location': '普林斯顿'
}
}
for username, user_info in users.items():
print("\nUsername:" + username)
full_name = user_info['first'] + " " + user_info['last']
location = user_info['location']
print("\tFull name:" + full_name.title())
result:
Username:爱因斯坦
Full name:阿尔伯特 爱因斯坦