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))

转载注明原文:python – 迭代关键字和defaultDict字典的价值 - 代码日志