- aDict = {'key1':'value1', 'key2':'value2', 'key3':'value3'}
- print '-----------dict-------------'
- for d in aDict:
- print "%s:%s" %(d, aDict[d])
- print '-----------item-------------'
- for (k,v) in aDict.items():
- print '%s:%s' %(k, v)
- #效率最高
- print '------------iteritems---------'
- for k,v in aDict.iteritems():
- print '%s:%s' % (k, v)
- #最笨的方法
- print '---------iterkeys---------------'
- for k in aDict.iterkeys():
- print '%s:%s' % (k, aDict[k])
- print '------------iterkeys, itervalues----------'
- for k,v in zip(aDict.iterkeys(), aDict.itervalues()):
- print '%s:%s' % (k, v)
结果:
- -----------dict-------------
- key3:value3
- key2:value2
- key1:value1
- -----------item-------------
- key3:value3
- key2:value2
- key1:value1
- ------------iteritems---------
- key3:value3
- key2:value2
- key1:value1
- ---------iterkeys---------------
- key3:value3
- key2:value2
- key1:value1
- ------------iterkeys, itervalues----------
- key3:value3
- key2:value2
- key1:value1
本文介绍了使用Python遍历字典的不同方法,包括直接遍历、利用items()方法、iteritems()迭代器方法、iterkeys()及itervalues()方法等,并比较了它们之间的效率。



1766

被折叠的 条评论
为什么被折叠?



