python使用多种方法对字典遍历

介绍4种方法,最后一种方法不能对字典遍历:
1.使用dict.keys()和dict.values()进行遍历

dict = {
    
    "name": 'zhangsan', 'sex': 'm'}
for key in dict.keys():
	print key
for value in dict.values():
	print value

输出结果分别为:
name sex
zhangsan m

2.使用dict.items()进行遍历

dict = {
    
    "name": 'zhangsan', 'sex': 'm'}
for item in dict.items():
	print item

输出结果为:
(‘name’, ‘zhangsan’)
(‘sex’, ‘m’)

3.使用dict.items()进行遍历键值对

dict = {
    
    "name": 'zhangsan', 'sex': 'm'}
for key, value in dict.items():
	print("key = %s, value = %s" % (key, value))

输出结果为:
key = name, value = zhangsan
key = sex, value = m

4.emumerate()函数,这个函数不能对字典进行遍历,只可以对可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

chars = ['a', 'b', 'c', 'd']
for i, chr in enumerate(chars):
    print("index = %d, value = %s" % (i, chr))

输出结果为:
index = 0 value = a
index = 1 value = b
index = 2 value = c
index = 3 value = d

猜你喜欢

转载自blog.csdn.net/qq_41542989/article/details/108974729