Search code examples
pythonloopsdictionarydictionary-comprehension

TypeError: 'int' object is not iterable when trying to reverse a dictionary in python


listyList = [1, 5, 7, 9999]
multiple = [(f, f*100) for f in listyList]
multipleDict = {f[0]:f[1] for f in multiple}

multipleDict = {v:k for k, v in multipleDict}

print (multipleDict[700])

I am a beginner and tried to reverse a dictionary similar to an example in a tutorial. As far as I can tell I should be iterating through a dictionary and not an int? yet I receive this error when I try to run it

Traceback (most recent call last):
  File "C:\Users\User\Desktop\test.py", line 5, in <module>
    multipleDict = {v:k for k, v in multipleDict}
  File "C:\Users\User\Desktop\test.py", line 5, in <dictcomp>
    multipleDict = {v:k for k, v in multipleDict}
TypeError: 'int' object is not iterable

Solution

  • I think it will help understand the error a little more if we look at a roughly equivalent for loop, first of all using a correct expression:

    for item in multipleDict.items():
        k, v = item
        ...
    

    Here, the items method of the dictionary returns an iterator over 2-element tuples of the form (key, value), and in each iteration of the for loop, the variable item contains just one of these 2-element tuples. This can then be unpacked into multiple variables (in this case, 2 variables) in an unpacking assignment -- which requires iterating over the elements of the tuple.

    One could also omit the item variable, and write simply:

    for k, v in multipleDict.items():
        ....
    

    and this is closer to what you would use in a dictionary comprehension.

    Now for the version that went wrong -- or a for loop equivalent of it. I'll go back to writing it using an item variable, although again, it doesn't require it.

    for item in mutipleDict:
        k, v = item
        ...
    

    When you iterate over a dictionary, you iterate over the keys, so this would also be equivalent to:

    for item in mutipleDict.keys():
        k, v = item
        ...
    

    In this case, the keys of your dictionary are just integers -- here 1, 5, 7, and 9999 (not necessarily in that order). So on the first iteration, item would contain one of these integers, and it is trying to unpack it into multiple variables. But you can't iterate over an integer, which is why you get the error that you saw.

    Going back to the original dictionary comprehension, the corrected version is just:

    multipleDict = {v:k for k, v in multipleDict.items()}