Georg Fritzsche
Georg Fritzsche

Reputation: 98984

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

With:

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

Why? How can i fix it?

Upvotes: 64

Views: 91792

Answers (3)

SilentGhost
SilentGhost

Reputation: 319531

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

Upvotes: 107

Nguai al
Nguai al

Reputation: 958

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

Upvotes: 3

Vlad Bezden
Vlad Bezden

Reputation: 89517

if you are using Python 3.6

from collections import defaultdict

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

Upvotes: 28

Related Questions