字典的遍历

<1> 遍历字典的key(键)

<2> 遍历字典的value(值)

<3> 遍历字典的项(元素)

<4> 遍历字典的key-value(键值对)

Demo

d = {'x':1, 'y':2, 'z':3}
print ("----------- 遍历字典的key(键)----------------")
for key in d.keys():
     print (key)
print ("----------- 遍历字典的value(值)----------------")
for value in d.values():
     print (value)
print ("----------- 遍历字典的项(元素)----------------")
for item in d.items():
     print (item)     
print("-----------遍历字典的key-value(键值对)-----------")
for key,value in d.items():
     print ("key=%s,values = %s"%(key,value)) 

 运行结果:

----------- 遍历字典的key(键)----------------
y
z
x
----------- 遍历字典的value(值)----------------
2
3
1
----------- 遍历字典的项(元素)----------------
('y', 2)
('z', 3)
('x', 1)
-----------遍历字典的key-value(键值对)-----------
key=y,values = 2
key=z,values = 3
key=x,values = 1

 

posted on 2017-03-15 16:26  LoaderMan  阅读(262)  评论(0编辑  收藏  举报

导航