Georg Fritzsche Georg Fritzsche - 1 year ago 109
Python Question

Iterating over key and value of defaultdict dictionaries

The following works as expected:

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

But this fails:

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

Why? How can i fix it?

Answer Source

you need to iterate over dict.iteritems():

for k,v in d.iteritems():               # will become d.items() in py3k
  print "%s - %s" % (str(k), str(v))

In Python 3 use: dict.items().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download