1.在列表中嵌套字典
字典列表:将字典存储在列表中
alien_0={
'color':'green',
'points':5
}
alien_1={
'color':'yellow',
'points':15
}
alien_2={
'color':'black',
'points':10
}
aliens=[alien_0,alien_1,alien_2]
for alien in aliens:
print(alien)
2.在字典中嵌套列表
将列表存储在字典中
每当需要在字典中讲一个键关联到多个值时,都可以在字典中嵌套一个列表
favorite_languages={
'jen':['python','ruby'],
#或者'sarah':'c';
'sarah':['c'],
'edward':['ruby','go'],
'phil':['python','haskell'],
}
for name,languages in favorite_languages.items():
if len(languages)>1:
print("\n"+name.title()+"'s favorite language are:")
for language in languages:
print("\t"+language.title())
else:
print("\n"+name.title()+"'s favorite language is:")
for language in languages:
print("\t"+language.title())
3.字典中嵌套字典
在字典中存储列表
一般字典中的结构最好相同,处理比较容易,如果键不同,可能处理更复杂
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("\tfullname:"+full_name.title())
print("\tlocation:"+location.title())
网友评论