有时需要将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套
包含字典的列表
player1 = {'color': 'green', 'points': 5}
player2 = {'color': 'yellow', 'points': 10}
player3 = {'color': 'red', 'points': 15}
players = [player1, player2, player3]
for player in players:
print(player)
out:
{'points': 5, 'color': 'green'}
{'points': 10, 'color': 'yellow'}
{'points': 15, 'color': 'red'}
创建一个用于存储玩家的空列表,不断添加append()可以使可以的
players = []
for player_number in range(30):
new_player = {'color': 'green', 'points': 5, 'speed': 'slow'}
players.append(new_player)
for player in players[:5]:
print(player)
print("...")
print("Total number of players: " + str(len(players)))
out:
{'color': 'green', 'speed': 'slow', 'points': 5}
{'color': 'green', 'speed': 'slow', 'points': 5}
{'color': 'green', 'speed': 'slow', 'points': 5}
{'color': 'green', 'speed': 'slow', 'points': 5}
{'color': 'green', 'speed': 'slow', 'points': 5}
...
Total number of players: 30
字典中存储列表
描述字典可以用列表存储信息
person_languages = {
'A': ['python', 'ruby'],
'B': ['c'],
'C': ['ruby', 'go'],
'D': ['python', 'java'],
}
for name ,languages in person_languages.items():
print("\n" + name.title() + "'s favorite languages are:")
for language in languages:
print("\t" + language.title())
out:
A's favorite languages are:
Python
Ruby
B's favorite languages are:
C
C's favorite languages are:
Ruby
Go
D's favorite languages are:
Python
Java
字典中包含字典
对于多个用户对应各自不同的信息,可以使用字典集合嵌套在字典中
game_name = {
'wanjia1': {
'first': 'albet',
'last': 'einstein',
'location': 'wuxi',
},
'wanjia2': {
'first': 'saeq',
'last': 'curie',
'location': 'paris',
},
}
for name,game_name_info in game_name.items():
print("\n 游戏名: " + name)
full_name = game_name_info['first'] + " " + game_name_info['last']
location = game_name_info['location']
print("\tFull name: " + full_name.title())
print("\tLocation: " + location.title())
out:
游戏名: wanjia1
Full name: Albet Einstein
Location: Wuxi
游戏名: wanjia2
Full name: Saeq Curie
Location: Paris