3

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] 

2 Answers 2

5

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] 
Sign up to request clarification or add additional context in comments.

Comments

4

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] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.