python遍历字典的四种方法
- 根据key值遍历
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
- 根据value遍历
>>> for value in a.values(): print(value) 1 2 3
- 根据字典项遍历
1 >>> for kv in a.items(): 2 print(kv) 3 4 ('a', '1') 5 ('b', '2') 6 ('c', '3')
- 根据字典键值对遍历
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