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?
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.
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}")
if you are using Python 3.6
from collections import defaultdict for k, v in d.items(): print(f'{k} - {v}')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With