python遍历字典的四种方法

  • 根据key值遍历
>>> a
{‘a‘: ‘1‘, ‘b‘: ‘2‘, ‘c‘: ‘3‘}
>>> for key in a:
       print(key+‘:‘+a[key])
 
a:1
b:2
c:3
>>> for key in a.keys():
       print(key+‘:‘+a[key])
 
a:1
b:2
c:3

根据value遍历

>>> for value in a.values():
       print(value)
 
1
2
3

根据字典项遍历

>>> for kv in a.items():
       print(kv)
 
(‘a‘, ‘1‘)
(‘b‘, ‘2‘)
(‘c‘, ‘3‘)

根据字典键值对遍历

>>> for key,value in a.items():
       print(key+‘:‘+value)
 
a:1
b:2
c:3
>>> for (key,value) in a.items():
       print(key+‘:‘+value)
 
a:1
b:2
c:3

相关推荐