以下按预期方式工作:
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
为什么呢?我该如何解决?
答案 0 :(得分:61)
你需要迭代dict.iteritems()
:
for k,v in d.iteritems(): # will become d.items() in py3k
print "%s - %s" % (str(k), str(v))
答案 1 :(得分:16)
如果您使用的是Python 3.6
from collections import defaultdict
for k, v in d.items():
print(f'{k} - {v}')
答案 2 :(得分:0)
如果要遍历单个集合中的单个项目:
from collections import defaultdict
for k, values in d.items():
for value in values:
print(f'{k} - {value}')