Home  >  Article  >  Backend Development  >  python3-How to store dictionaries in lists

python3-How to store dictionaries in lists

高洛峰
高洛峰Original
2017-03-26 18:29:074915browse

This article mainly introduces in detail the relevant information about the method of storing dictionaries in python3-list. Friends in need can refer to it

# Auther: Aaron Fan

#示例1:
#定义几个字典
alien_0 = {"color":"green", "points":5}
alien_1 = {"color":"yellow", "points":10}
alien_2 = {"color":"red", "points":15}

#把字典存入到列表aliens中
aliens = [alien_0, alien_1, alien_2]

#遍历这个列表
for alien in aliens:
   print(alien)

#示例2:
#创建一个用于存储外星人的空列表
aliens = []
#创建30个绿色的外星人
for alien_number in range(30):
   new_alien = {"color":"green", 'points':5, 'speed':'slow'}
   aliens.append(new_alien)
#显示前5个外星人
for alien in aliens[:5]:
   print(alien)
print("...")
#显示一共创建了多少个外星人
print("外星人的数量是: %d" % len(aliens))

#示例3:
#创建一个用于存储外星人的空列表
aliens = []
#创建30个绿色的外星人
for alien_number in range(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
   elif alien['color'] == 'yellow':
       alien['color'] = 'red'
       alien['speed'] = 'fast'
       alien['points'] = 15

#显示前5个外星人
for alien in aliens[:5]:
   print(alien)
print("...")

The above is the detailed content of python3-How to store dictionaries in lists. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn