python – 迭代关键字和defaultDict字典的价值

以下工作如预期:

d = [(1,2), (3,4)]
for k,v in d:
  print "%s - %s" % (str(k), str(v))

但这失败了:

d = collections.defaultdict(int)
d[1] = 2
d[3] = 4
for k,v in d:
  print "%s - %s" % (str(k), str(v))

附:

Traceback (most recent call last):  
 File "<stdin>", line 1, in <module>  
TypeError: 'int' object is not iterable 

为什么?我该如何解决?

你需要迭代dict.iteritems():

for k,v in d.iteritems():               # will become d.items() in py3k
  print "%s - %s" % (str(k), str(v))
http://stackoverflow.com/questions/2768188/iterating-over-key-and-value-of-defaultdict-dictionaries

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:python – 迭代关键字和defaultDict字典的价值