1.字典列表
# create a list to store all aliens
aliens = []
# create initial 30 green aliens
for alien_number in range(0, 30):
new_alien = {
'color': 'green',
'points': 5,
'speed': 'slow',
}
aliens.append(new_alien)
# level up! some of them has upgraded now!
for alien in aliens[0:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['points'] = 10
alien['speed'] = 'medium'
# show first 5 aliens
for alien in aliens[0:5]:
print(alien)
⚠️:列表中添加元素(字典)
# create a list to store all aliens
aliens = []
and
aliens.append(new_alien)
2.在字典中储存列表
# store the information of pizzas
pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese']
}
# describe the pizza you just made
print('You ordered a ' + pizza['crust'] + '-crust pizza with the following toppings')
# list all the toppings
for topping in pizza['toppings']:
print("\t" + topping)
⚠️:遍历列表时,需指定是字典中的列表
for topping in pizza['toppings']:
3.字典中的字典
# define a dictionary with two sub-dictionaries as keys
users = {
'HalO': {
'first': 'Bing',
'last': 'Lucas',
'location': 'China',
},
'404': {
'first': 'Qing',
'last': 'Linnea',
'location': 'England',
},
}
# try to get the value inside the dictionary
for user_name, user_info in users.items():
print("\nUsername: " + user_name)
full_name = user_info['last'] + " " + user_info['first']
location = user_info['location']
print("\tFull name: " + full_name.title())
print("\tLocation: " + location)