1

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.

cs95
  • 379,657
  • 97
  • 704
  • 746
MAUCA
  • 49
  • 11

1 Answers1

3

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
cs95
  • 379,657
  • 97
  • 704
  • 746
  • Thank you, for the first case where th = [1,2,3] can you also use dict.get()? like what would be a faster way instead of doing the loop. – MAUCA Sep 01 '17 at 03:53
  • @MauricioCastaneda It will only work in the first case. For the second... you'll need to look here: https://stackoverflow.com/questions/483666/python-reverse-invert-a-mapping or stick to your current implementation. – cs95 Sep 01 '17 at 03:54