MAUCA
MAUCA

Reputation: 59

TypeError: 'int' is not iterable when trying to iterate over a dictionary

I'm somewhat new to python, and I have been trying to find a way to iterate over a dictionary whose keys are as follow:

r_alpha: {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 18: 'r', 19: 's', 20: 't', 21: 'u', 22: 'v', 23: 'w', 24: 'x', 25: 'y', 26: 'z'}

lets assume the following: I have a list and I want to find if the value of the list is in the dictionary key and print the value for that key but this happens:

th = [1,2,3]
for item in th:
for keys, values in r_alpha.items():
        if item in keys:
            print(values)

I receive the following error, pointing to line 4 (if item in keys:) TypeError: argument of type 'int' is not iterable

If I change that list to string values I actually get the keys for the values that are strings like this:

th = ['a','b','c']
for item in th:
for keys, values in r_alpha.items():
        if item in values:
            print(keys)

it prints: 1 2 3

can someone please help me and tell me what I'm doing wrong? or how can I iterate over the int keys of the dictionary so it returns the values.

Upvotes: 1

Views: 1926

Answers (1)

cs95
cs95

Reputation: 402844

The reason for your error is because you are iterating over the keys in a loop, and at each iteration compare the key to some other value using the in operator which is meant for membership tests with iterables. Since your keys are integers (not iterables), this will obviously not work.


There's no need to iterate over the keys of a dictionary when they support constant time lookup.

for item in th:
    if item in r_alpha:
        print(r_alpha[item])
a
b
c

Alternatively, you could use dict.get to remove the if condition.

for item in th:
    print(r_alpha.get(item))
a
b
c

Upvotes: 3

Related Questions