1.遍历所有的键值对
要编写用于遍历字典的for循环,可生明两个变量,用于存储键值对中的键和值。对于这两个变量可以使用任何名称。for语句的第二部分包含字典名和方法items(),它返回一个键值对列表。for循环依次将每个键值对存储到指定的两个变量中。
#helloword.py
user_0={
'username':'efermi',
'first':'enrico',
'last':'fermi'
}
for key,value in user_0.items():
print("\nkey: "+key)
print("value: "+value)
输出为:
D:\www>python helloword.py
key: username
value: efermi
key: first
value: enrico
key: last
value: fermi
2.遍历字典中的所有键
使用方法keys()
#helloword.py
user_0={
'username':'efermi',
'first':'enrico',
'last':'fermi'
}
for key in user_0.keys():
print("\nkey: "+key.title())
输出为:
D:\www>python helloword.py
key: Username
key: First
key: Last
遍历字典时会默认遍历所有的键,因此如果将上述代码中的for key in user_0.keys(): 改为for key in user_0: 输出将不变
实例:
#helloword.py
favorite_languages={
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python'
}
friends=['phil','sarah']
for name in favorite_languages.keys():
print(name.title())
if name in friends:
print("Hi "+name.title()+",I see your favorite language is "+favorite_languages[name].title()+"!")
输出为:
D:\www>python helloword.py
Jen
Sarah
Hi Sarah,I see your favorite language is C!
Edward
Phil
Hi Phil,I see your favorite language is Python!
**你还可以使用Keys确定某个人是否接受了调查,下面代码确定erin是否接受了调查
#helloword.py
favorite_languages={
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python'
}
if 'erin' not in favorite_languages.keys():
print("erin,please take our poll!")
输出为:
D:\www>python helloword.py
erin,please take our poll!
注:方法keys()并非只能用于遍历,实际上它返回一个列表,其中包含字典中的所有键
2.按顺序遍历字典中的所有键
要以特定的顺序返回元素,一种是在for循环中对返回的键进行排序。可使用函数sorted()来获得按特定顺序排序的键列表的副本
#helloword.py
favorite_languages={
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python'
}
for name in sorted(favorite_languages.keys()):
print(name.title()+",thank you for taking the poll.")
输出为:
D:\www>python helloword.py
Edward,thank you for taking the poll.
Jen,thank you for taking the poll.
Phil,thank you for taking the poll.
Sarah,thank you for taking the poll.
3.遍历字典中所有值
可使用方法values(),它返回一个值列表,而不包含任何键
#helloword.py
favorite_languages={
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python'
}
for language in favorite_languages.values():
print(language.title())
输出为:
D:\www>python helloword.py
Python
C
Ruby
Python
这种做法是提取字典中所有的值,而没有考虑是否重复。
为剔除重复项,可使用集合(set),集合类似于列表,但每个元素都必须是独一无二的。
#helloword.py
favorite_languages={
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python'
}
for language in set(favorite_languages.values()):
print(language.title())
输出为:
D:\www>python helloword.py
Ruby
Python
C