字典的关键字参数,可以省略key的引号,针对字符串
>>> dict(one='1', two='2')
{'two': '2', 'one': '1'}
遍历python字典几种方法
遍历dict的时候,养成使用 for k in d.keys() 的习惯。
has_key()方法效率要比 key in xxx.keys()高
脚本:
- #!/usr/bin/python
- dict={"a":"apple","b":"banana","o":"orange"}
- print "##########dict######################"
- for i in dict:
- print "dict[%s]=" % i,dict[i]
- print "###########items#####################"
- for (k,v) in dict.items():
- print "dict[%s]=" % k,v
- print "###########iteritems#################"
- for k,v in dict.iteritems():
- print "dict[%s]=" % k,v
- print "###########iterkeys,itervalues#######"
- for k,v in zip(dict.iterkeys(),dict.itervalues()):
- print "dict[%s]=" % k,v
执行结果:
- ##########dict######################
- dict[a]= apple
- dict[b]= banana
- dict[o]= orange
- ###########items#####################
- dict[a]= apple
- dict[b]= banana
- dict[o]= orange
- ###########iteritems#################
- dict[a]= apple
- dict[b]= banana
- dict[o]= orange
- ###########iterkeys,itervalues#######
- dict[a]= apple
- dict[b]= banana
- dict[o]= orange
本文出自 “Larry学习之路” 博客,请务必保留此出处http://5iqiong.blog.51cto.com/2999926/806230
That which didn't kill me makes me stronger