一、字典列表
外星人字典包含全部外星人,而其中的每个外星人都是一个字典用来存储外星人的所有信息
alien_0 = {'color':'green','point':5}
alien_1 = {'color':'blue','point':12}
alien_2 = {'color':'black','point':10}
aliens = [alien_0,alien_1,alien_2]
for alien in aliens:
print(alien)
运行结果:
{‘color’: ‘green’, ‘point’: 5}
{‘color’: ‘blue’, ‘point’: 12}
{‘color’: ‘black’, ‘point’: 10}
二、在字典中存储列表
有时候需要将列表存储在字典中,而不是将字典存储在列表中。例如你如何描述顾客点的披萨呢?如果使用列表只能存储要添加的披萨配料。如果使用字典,就不仅可在其中配料列表,还可以包含其他有关披萨的描述
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 lnguages are:")
for language in languages:
print("\t" + language.title())
运行结果:
Jen’s favorite lnguages are:
Python
Ruby
Sarah’s favorite lnguages are:
C
Edward’s favorite lnguages are:
Ruby
Go
Phil’s favorite lnguages are:
Python
Haskell
三、字典中存储字典
如果网站有多个用户,每个都有独特的用户名,可在字典中将用户名作为键,然后每个用户的信息存储在一个字典中,并将该字典作为与用户名相关联的值
users = {
'aeinstein':{
'first':'albert',
'last':'einstein',
'location':'princeton',
},
'mcurie':{
'first':'marie',
'last':'curie',
'location':'paris',
}
}
for username,user_info in users.items():
print("\n username:" + username)
full_name = user_info['first'] + " " +user_info['last']
location = user_info['location']
print("\tFull name:" + full_name.title())
print("\rLocation:" + location.title())
运行结果:
username:aeinstein
Full name:Albert Einstein
Location:Princeton
username:mcurie
Full name:Marie Curie
Location:Paris