再字典中存储列表:
经常需要再列表中包含大量的字典,而其中每个字典都包含“特定属性”的众多信息。
# 创建30个外星人
aliens = []
for alien_number in range(0, 30):
new_alien = {
'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)
# 修改部分外星人数据
for alien in aliens[0:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = '10'
print(alien)
print("...")
# 打印剩下的所有列表内的字典
for print_result in aliens[4:30]:
print(print_result)
{
'color': 'yellow', 'points': '10', 'speed': 'medium'}
{
'color': 'yellow', 'points': '10', 'speed': 'medium'}
{
'color': 'yellow', 'points': '10', 'speed'