字典有两部分,一个item,一个value
列表中存储字典
创建一个用于存储外星人的空列表
aliens = []
创建30个绿色的外星人
❶ for alien_number in range(30):
❷ new_alien = {‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
❸ aliens.append(new_alien)
[ {‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’},
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’},
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’},
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’},
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}]
字典存储列表:
favorite_languages = {
‘jen’: [‘python’, ‘ruby’],
‘sarah’: [‘c’],
‘edward’: [‘ruby’, ‘go’],
‘phil’: [‘python’, ‘haskell’],
}
字典中存储字典:
users = {
‘aeinstein’: {
‘first’: ‘albert’,
‘last’: ‘einstein’,
‘location’: ‘princeton’,
},
‘mcurie’: {
‘first’: ‘marie’,
‘last’: ‘curie’,
‘location’: ‘paris’,
},
}
❶ 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())
print("\tLocation: " + location.title())