Home  >  Article  >  Backend Development  >  Summary of several methods for traversing python dictionary

Summary of several methods for traversing python dictionary

高洛峰
高洛峰Original
2017-02-23 11:49:511922browse

The editor below will bring you a summary of several methods of traversing python dictionaries (recommended). The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let’s follow the editor and take a look.

is as follows:

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)


Running results:

<pre name="code" class="python">-----------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

The above article traverses several python dictionaries The method summary (recommendation) is all the content shared by the editor. I hope it can give you a reference, and I also hope you will support the PHP Chinese website.

For more summary of several methods of traversing python dictionary and related articles, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn