Key: username Value: efermi Key: first Value: enrico Key: last Value: fermi
5.2 遍历字典中所有的键(keys()方法)
在不需要使用字典中的值时,方法keys()很有用:
1 2 3 4 5 6 7 8 9
favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } for name in favorite_languages.keys(): print(name.title())
上面的代码提取字典中的所有键,并依次将它们存储到变量name中,输出结果如下:
1 2 3 4
Jen Sarah Edward Phil
注意,遍历字典时,会默认遍历所有的键,因此,如果将上述代码中的for name in favorite_languages.keys(): 替换为for name in favorite_languages:,则输出结果不变。
5.3 遍历字典中所有的值(values()方法,函数set())
在不需要使用字典中的键时,方法values()很有用:
1 2 3 4 5 6 7 8 9 10
favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } print("The following languages have been mentioned:") for language in favorite_languages.values(): print(language.title())
这条for语句提取字典中的每个值,并将它们依次存储到变量language中。输出结果如下:
1 2 3 4 5
The following languages have been mentioned: Python C Ruby Python
favorite_languages = { 'jen': 'python', 'sarah': 'c', 'edward': 'ruby', 'phil': 'python', } print("The following languages have been mentioned:") for language inset(favorite_languages.values()): print(language.title())
此时输出的结果是一个不重复的列表,如下所示:
1 2 3 4
The following languages have been mentioned: Ruby Python C
pizza = { 'crust': 'thick', 'toppings': ['mushrooms', 'extra cheese'], } print("You ordered a " + pizza['crust'] + "-crust pizza " + "with the following toppings:") for topping in pizza['toppings']: print("\t" + topping)
此时的输出结果为:
1 2 3
You ordered a thick-crust pizza with the following toppings: mushrooms extra cheese
每当需要在字典中将一个键关联到多个值时,都可以在字典中嵌套一个列表,下面是一个经典的例子:
1 2 3 4 5 6 7 8 9 10 11
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())
此时的输出结果为:
1 2 3 4 5 6 7 8 9 10 11 12
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