Python3之字典遍历的5种方法

dict1={1:"a",2:"b",3:"c"}

print("way1:遍历键值对-1")
for k,v in dict1.items():
    print(k,v)

print("way2:遍历键值对-2")
for item in dict1.items():
    print(item[0],item[1])

#dict1[]而不是dict(),否则会报错,object is not callable,变量名也不要随意命名
print("way3:遍历键-1")
for k in dict1:
    print(k, dict1[k])

print("way4:遍历键-2")
for k in dict1.keys():
    print(k, dict1[k])

print("way5:遍历值")
for v in dict1.values():
    print(v)

结果:

way1:遍历键值对-1
1 a
2 b
3 c
way2:遍历键值对-2
1 a
2 b
3 c
way3:遍历键-1
1 a
2 b
3 c
way4:遍历键-2
1 a
2 b
3 c
way5:遍历值
a
b
c