generate a new dictionary based on list of values

Question:

I have an input dictionary d1 and list l1 and want to generate output dictionary d2.

d1 = {'A1':['b1','b2','b3'], 'A2':['b2', 'b3'], 'A3':['b1', 'b5']}
l1 = ['b2', 'b5', 'b1', 'b3']

Output dictionary

d2 = {'b2':['A1','A2'], 'b5':['A3'], 'b1':['A1','A3'], 'b3':['A1','A2']}

In output dictionary all values of list l1 act as keys, for the values of dictionary d2 we search the particular key in d1 dictionary values, if this key is present in dictionary values we will select the corresponding key from the dictionaryd1. For example, for key b2, we search it in dictionary values, as it is present in values of ‘A1’ keys and ‘A2’ keys, so we select ‘A1’ and ‘A2’ from d1. Is there any way to do it?

Asked By: Noorulain Islam

||

Answers:

You can use a simple dictionary comprehension with a nested list comprehension:

>>> {value: [key for key in d1 if value in d1[key]] for value in l1}
{'b2': ['A1', 'A2'], 'b5': ['A3'], 'b1': ['A1', 'A3'], 'b3': ['A1', 'A2']}
Answered By: A.J. Uppal
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.