views:

137

answers:

1

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?

+4  A: 

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))
SilentGhost
Thanks. Why does it work with an implicitly created dictionary though? Are these inconsistencies / implementation differences?
Georg Fritzsche
@gf Your first example is a list, not a dictionary.
Daniel Stutzbach
@Daniel: Ouch, thanks :)
Georg Fritzsche