Geo*_*che 36 python dictionary iterator
以下按预期工作:
d = [(1,2), (3,4)]
for k,v in d:
print "%s - %s" % (str(k), str(v))
Run Code Online (Sandbox Code Playgroud)
但这失败了:
d = collections.defaultdict(int)
d[1] = 2
d[3] = 4
for k,v in d:
print "%s - %s" % (str(k), str(v))
Run Code Online (Sandbox Code Playgroud)
附:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
Run Code Online (Sandbox Code Playgroud)
为什么?我该如何解决?
Sil*_*ost 66
你需要迭代dict.iteritems():
for k,v in d.iteritems(): # will become d.items() in py3k
print "%s - %s" % (str(k), str(v))
Run Code Online (Sandbox Code Playgroud)
Vla*_*den 18
如果您使用的是Python 3.6
from collections import defaultdict
for k, v in d.items():
print(f'{k} - {v}')
Run Code Online (Sandbox Code Playgroud)