Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python reverse dictionary lookup in list comprehension

I have the following dictionary:

d = {}
d[1] = 'a'
d[2] = 'b'
d[3] = 'c'
d[4] = 'd'

I’d like to perform a reverse dictionary lookup for each character in a string:

input_string = "bad"

I get different results when I do this in a list comprehension as opposed to a nested for loop, and I don’t understand why. As I understand, the list comprehension and the nested for loop should yield identical results. The list comprehension yields a list whose results are not in the order I would expect. My desired result here is that which is provided by the nested for loop, however I prefer to use the list comprehension to accomplish that. Perhaps this has something to do with python dictionary order of which I am unaware?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

result1 = [key for key, value in d.items() for i in input_string if i == value]
print(result1)


> [1, 2, 4]


result2 = list()
for i in input_string:
    for key, value in d.items():
        if i == value:
            result2.append(key)

print(result2)

> [2, 1, 4]

>Solution :

In order to mimic the traditional loop, the other loop should be over input_string, right?

out = [k for i in input_string for k,v in d.items() if i==v]

Output:

[2, 1, 4]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading