zza = {'crust':'thick',
'toppings':['mushroom','extra cheese'],
}
print("you ordered a "+pizza['crust']+"-crust pizza " +
"with the following toppings:") #打印pizza中crust键中的内容
for topping in pizza['toppings']:
print("\t" + topping) #遍历pizza中toppings键中的内容并将其打印出来
#运行结果为:
you ordered a thick-crust pizza with the following toppings:
mushroom
extra cheese
每当在字典中想要用一个键关联多个值时就可以使用嵌套语句来执行,在之前的喜欢的语言程序中使用嵌套的话在遍历字典的时候,与每个被调查者相关联的都是一个语言列表,所以每一个人就可以选择多个语言
1 favourite_languages = {
2 'jen' : ['python','ruby'],
3 'sarah' : ['c'],
4 'edward' : ['ruby','go'],
5 'phil' : ['python','haskell'],
6 }
7 for name,languages in favourite_languages.items():
8 print("\n" + name.title() + "'s favourite language is")
9 for language in languages:
10 print("\t" + language.title())
11 #运行结果为:
12 Phil's favourite language is
13 Python
14 Haskell
15
16 Sarah's favourite language is
17 C
18
19 Jen's favourite language is
20 Python
21 Ruby
22
23 Edward's favourite language is
24 Ruby
25 Go
每一个关联的键都对应好几个值,第一个for循环用来输出人名,第二个for循环用来输出,每个人名下喜欢的全部语言
字典中储存字典
在字典中嵌套字典,这样子做的话可以使得代码很快的复杂起来,例如多个网站有多个用户,每一个用户都有自己独特的用户名,可在字典中将用户名作为键,然后将用户的信息储存到在一个字典中,并将这个字典和用户名键关联在一起
1 users = {
2 'aeinstein': {
3 'first': 'albert',
4 'last': 'einstein',
5 'location': 'princetion',
6 },
7 'mcurie': {
8 'first': 'marie',
9 'last': 'curie',
10 'location': 'pariis',
11 },
12 }
13
14 for user_name, user_info in users.items():
15 print("\nUsername:" + user_name)
16 full_name = user_info['first'] + " " + user_info['last']
17 location = user_info['location']
18
19 print("\tfull name: " + full_name.title())
20 print("\tlocation: " + location.title())
21 #运行结果为:
22 Username:mcurie
23 full name: Marie Curie
24 location: Pariis
25
26 Username:aeinstein
27 full name: Albert Einstein
28 location: Princetion