有时需要将一系列字典存储在列表中,或将列表作为值存储在字典中,这成为嵌套。可以在列表中嵌套字典、在字典中嵌套列表甚至在字典中嵌套字典。
1.字典列表
#helloword.py
alien_0={'color':'green','points':5}
alien_1={'color':'yellow','points':5}
alien_2={'color':'red','points':15}
aliens=[alien_0,alien_1,alien_2]
for alien in aliens:
print(alien)
输出为:
D:\www>python helloword.py
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 5}
{'color': 'red', 'points': 15}
经常需要在列表中包含大量的字典,而其中每个字典都包含特定对象的众多信息。
实例:
#helloword.py
aliens=[]
for alien_number in range(30):
new_alien={'color':'green','points':5,'speed':'slow'}
aliens.append(new_alien)
for alien in aliens[:5]:
print(alien)
print("...")
print("Total number of aliens: "+str(len(aliens)))
输出为:
D:\www>python helloword.py
{'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'}
...
Total number of aliens: 30
2、在字典中存储列表
每当需要在字典中将一个键关联到多个值时,都可以在字典中嵌套一个列表
#helloword.py
pizza={
'crust':'thick',
'toppings':['mushrooms','extra cheese']
}
print("You ordered a "+pizza['crust']+"-crust pizza "+"with the follwing toppings:")
for topping in pizza['toppings']:
print("\t"+topping)
输出为:
D:\www>python helloword.py
{'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'}
...
Total number of aliens: 30
D:\www>python helloword.py
You ordered a thick-crust pizza with the follwing toppings:
mushrooms
extra cheese
实例:
#helloword.py
favorite_languages={
'jen':['python','ruby'],
'sarah':['c'],
'edward':['ruby','go'],
'phil':['python','haskell']
}
for name,languages in favorite_languages.items():
print("\n"+name.title()+"'s favorite languages are:")
for language in languages:
print("\t"+language.title())
输出为:
D:\www>python helloword.py
Jen's favorite languages are:
Python
Ruby
Sarah's favorite languages are:
C
Edward's favorite languages are:
Ruby
Go
Phil's favorite languages are:
Python
Haskell
3、在字典中存储字典
例如:如果有多个网站用户,每个都有独特的用户名,可在字典中将用户名作为键,然后将每位用户的信息存储在一个字典中,并将该字典作为与用户名相关联的值。
#helloword.py
users={
'aeinatein':{
'first':'albert',
'last':'einstein',
'location':'princeton'
},
'mcurie':{
'first':'marie',
'last':'curie',
'location':'paris'
}
}
for username,user_info in users.items():
print("\nUsername: "+username)
fullname=user_info['first']+" "+user_info['last']
location=user_info['location']
print("\tFull name: "+fullname.title())
print("\tLocation: "+location.title())
输出为:
D:\www>python helloword.py
Username: aeinatein
Full name: Albert Einstein
Location: Princeton
Username: mcurie
Full name: Marie Curie
Location: Paris