能够使用一个 for 循环以及方法 items() 来遍历这个字典的键值对。bash
dict = {'evaporation': '蒸发',
'carpenter': '木匠'}
for key, value in dict.items():
print('key=' + key)
print('value=' + value)
复制代码
运行结果:函数
key=evaporation value=蒸发 key=carpenter value=木匠ui
key、value 这两个变量能够任意命名,好比下面的这个示例使用了 word 与 explain:spa
dict = {'evaporation': '蒸发',
'carpenter': '木匠'}
for word, explain in dict.items():
print('word=' + word)
print('explain=' + explain)
复制代码
运行结果:code
word=evaporation explain=蒸发 word=carpenter explain=木匠cdn
良好的命名习惯,能够编写出让人更容易理解的代码。blog
使用方法 keys() ,能够遍历字典中的键。排序
dict = {'evaporation': '蒸发',
'carpenter': '木匠'}
for word in dict.keys():
print(word.title())
复制代码
运行结果:字符串
Evaporation Carpenterstring
由于遍历字典时, 会默认遍历全部的键。因此,咱们能够省略方法 keys() 。
for word in dict:
print(word.title())
复制代码
运行结果与上一示例相同。
方法 keys() 还能够用在条件表达式中,用于判断 key 在字典中是否存在。
dict = {'evaporation': '蒸发',
'carpenter': '木匠'}
print('carpenter' in dict)
复制代码
运行结果:
True
能够在 for 循环中对返回的键进行排序,能够使用 sorted() 函数。
dict = {'evaporation': '蒸发',
'carpenter': '木匠'}
for word in sorted(dict):
print('word:' + word)
复制代码
运行结果:
word:carpenter word:evaporation
可以使用 values() 方法来遍历字典的值。
dict = {'evaporation': '蒸发',
'carpenter': '木匠'}
for explain in dict.values():
print('explain:' + explain)
复制代码
运行结果:
explain:蒸发 explain:木匠
有时候须要返回不重复的值。这时,咱们能够使用集 合( set) 。 集合相似于列表, 但它所包含的每一个元素,都必须是独一无二的。
dict = {'evaporation': '蒸发',
'carpenter': '木匠',
'millman': '木匠'}
print('【包含重复】' + str(dict.values()))
print('【剔除重复】' + str(set(dict.values())))
复制代码
运行结果:
【包含重复】dict_values(['蒸发', '木匠', '木匠']) 【剔除重复】{'蒸发', '木匠'}
注意: 字典的 values() 的字符串化与 set() 不一样。