Python – Map a dictionary to a data frame when the dictionary key is a list

Map a dictionary to a data frame when the dictionary key is a list… here is a solution to the problem.

Map a dictionary to a data frame when the dictionary key is a list

I have a dictionary where the value is a list:

dict = {1: ['a','b'], 2:['c', 'd']}

I want to map the dictionary to col1 of the data frame.

col1    
 a     
 c     

If the value of col1

is one of the values of my dictionary, then I want to replace the value of col1 with the value of the dictionary key.

Like this, my data frame will become:

col1
 1
 2

Thanks in advance

Solution

I’ll convert the dictionary the right way :

mapping = {}
for key, values in D.items():
    for item in values:
        mapping[item] = key

And then

df['col1'] = df['col1'].map(mapping)

Related Problems and Solutions