Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 305
Georg Fritzsche Avatar asked May 04 '10 19:05

Georg Fritzsche


People also ask

Can you iterate over a dictionary?

You can loop through a dictionary by using a for loop. When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.


2 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}") 
like image 125
SilentGhost Avatar answered Sep 25 '22 01:09

SilentGhost


if you are using Python 3.6

from collections import defaultdict  for k, v in d.items():     print(f'{k} - {v}') 
like image 24
Vlad Bezden Avatar answered Sep 22 '22 01:09

Vlad Bezden