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?
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]
CodePudding user response:
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]