遍历python字典几种方法 分类: python ...

字典的关键字参数,可以省略key的引号,针对字符串 

>>> dict(one='1', two='2') 

{'two': '2', 'one': '1'} 


遍历python字典几种方法


遍历dict的时候,养成使用 for k in d.keys() 的习惯。

has_key()方法效率要比 key in xxx.keys()高


脚本:

 
   
  1. #!/usr/bin/python 
  2. dict={"a":"apple","b":"banana","o":"orange"
  3.  
  4. print "##########dict######################" 
  5. for i in dict: 
  6.         print "dict[%s]=" % i,dict[i] 
  7.  
  8. print "###########items#####################" 
  9. for (k,v) in  dict.items(): 
  10.         print "dict[%s]=" % k,v 
  11.  
  12. print "###########iteritems#################" 
  13. for k,v in dict.iteritems(): 
  14.         print "dict[%s]=" % k,v 
  15.  
  16. print "###########iterkeys,itervalues#######" 
  17. for k,v in zip(dict.iterkeys(),dict.itervalues()): 
  18.         print "dict[%s]=" % k,v 

执行结果:

 
   
  1. ##########dict###################### 
  2. dict[a]= apple 
  3. dict[b]= banana 
  4. dict[o]= orange 
  5. ###########items##################### 
  6. dict[a]= apple 
  7. dict[b]= banana 
  8. dict[o]= orange 
  9. ###########iteritems################# 
  10. dict[a]= apple 
  11. dict[b]= banana 
  12. dict[o]= orange 
  13. ###########iterkeys,itervalues####### 
  14. dict[a]= apple 
  15. dict[b]= banana 
  16. dict[o]= orange 

 

本文出自 “Larry学习之路” 博客,请务必保留此出处http://5iqiong.blog.51cto.com/2999926/806230

That which didn't kill me makes me stronger

转载于:https://www.cnblogs.com/think1988/archive/2013/01/22/4628243.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值