迭代defaultdict词典的键和值

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)

  • @adam答案将其作为评论 - 现在是**d.items()**而不是d.iteritems(). (14认同)
  • @gf你的第一个例子是列表,而不是字典. (11认同)
  • 什么版本的python?我错过了一个导入?当我尝试在d.iteritems()中使用iteritems`d = defaultdict(list)for i时出现错误:AttributeError:'collections.defaultdict'对象没有属性'iteritems' (2认同)

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)