Iterating over key and value of defaultdict dictionaries

PythonDictionaryIterator

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

if you are using Python 3.6

from collections import defaultdict

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

Solution 3 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGeorg FritzscheView Question on Stackoverflow
Solution 1 - PythonSilentGhostView Answer on Stackoverflow
Solution 2 - PythonVlad BezdenView Answer on Stackoverflow
Solution 3 - PythonNguai alView Answer on Stackoverflow