【发布时间】:2010-11-03 21:23:47
【问题描述】:
我在python中以多少种方式遍历字典???
【问题讨论】:
-
你不是已经问过这个了吗?:stackoverflow.com/questions/1006575/…
-
另外,它重复了这个问题:stackoverflow.com/questions/380734/…
标签: python dictionary traversal
我在python中以多少种方式遍历字典???
【问题讨论】:
标签: python dictionary traversal
【讨论】:
多种方式!
testdict = {"bob" : 0, "joe": 20, "kate" : 73, "sue" : 40}
for items in testdict.items():
print (items)
for key in testdict.keys():
print (key, testdict[key])
for item in testdict.iteritems():
print item
for key in testdict.iterkeys():
print (key, testdict[key])
仅此而已,但它开始从这些简单的方式转向更复杂的方式。所有代码都经过测试。
【讨论】:
http://docs.python.org/tutorial/datastructures.html#looping-techniques
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.iteritems():
... print k, v
...
gallahad the pure
robin the brave
【讨论】: