Reputation: 2273
I have a list1 of values:
['A','B','C','D']
And I have a dict
{1: ['A','F'],2:['B','J'],3:['C','N'],4:['D','X']}
I would like to obtain the key for every value in the list:
I tried :
[dict1[x] for x in list]
However ouputs an error because I am not considering the fact the dict value is a list not a single value. How could I achieve this?
My desired output would be a list with the keys of the list1 values:
[1,2,3,4]
Upvotes: 3
Views: 44
Reputation: 26039
You can use a list-comprehension:
[k for x in lst for k, v in d.items() if x in v]
Example:
lst = ['A','B','C','D']
d = {1: ['A','F'],2:['B','J'],3:['C','N'],4:['D','X']}
print([k for x in lst for k, v in d.items() if x in v])
# [1, 2, 3, 4]
Upvotes: 5
Reputation: 71451
You can flatten the dictionary and use it as a lookup:
data = ['A','B','C','D']
d = {1: ['A','F'],2:['B','J'],3:['C','N'],4:['D','X']}
new_d = {i:a for a, b in d.items() for i in b}
result = [new_d[i] for i in data]
Output:
[1, 2, 3, 4]
Upvotes: 4