Iterating over key and value of defaultdict dictionaries

Question:

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

With:

Traceback (most recent call last):  
 File "<stdin>", line 1, in <module>  
TypeError: 'int' object is not iterable 

Why? How can i fix it?

Asked By: Georg Fritzsche

||

Answers:

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

Update: in py3 V3.6+

for k,v in d.items():
  print (f"{k} - {v}")
Answered By: SilentGhost

if you are using Python 3.6

from collections import defaultdict

for k, v in d.items():
    print(f'{k} - {v}')
Answered By: Vlad Bezden

If you want to iterate over individual item on an individual collection:

from collections import defaultdict

for k, values in d.items():
    for value in values:
       print(f'{k} - {value}')
Answered By: Nguai al
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.