(1)遍歷key值
在使用上,for key in a和 for key in a.keys():完全等價。
1 >>> a 2 {'a': '1', 'b': '2', 'c': '3'} 3 >>> for key in a: 4 print(key+':'+a[key]) 5 6 a:1 7 b:2 8 c:3 9 >>> for key in a.keys(): 10 print(key+':'+a[key]) 11 12 a:1 13 b:2 14 c:3
(2)遍歷value值
1 >>> for value in a.values(): 2 print(value) 3 4 1 5 2 6 3
(3)遍歷字典項
1 >>> for kv in a.items(): 2 print(kv) 3 4 ('a', '1') 5 ('b', '2') 6 ('c', '3')
(4)遍歷字典健值
在使用上for key,value in a.items()與for (key,value) in a.items()完全等價
1 >>> for key,value in a.items(): 2 print(key+':'+value) 3 4 a:1 5 b:2 6 c:3 7 >>> for (key,value) in a.items(): 8 print(key+':'+value) 9 10 a:1 11 b:2 12 c:3