Fill dictionary with value from the same row, but different column

  • A+

Lately I've been trying to map some values, so I'm trying to create a dictionary to do so. The odd thing is my DataFrame has a column made of lists, and DataFrames are always a bit awkward with lists. The DataFrame has the following structure:

    rules          procedure ['10','11','12']       1 ['13','14']            2 ['20','21','22','24']  3 

So I want to create a dictionary that maps '10' to 1, '14' to 2, and so on. I tried the following:

dicc=dict() for j in df['rules']:     for i,k in zip(j,df.procedure):         dicc[i]=k 

But that isn't making it. Probably something to do with indexes. What am I missing?

Edit: I'm trying to create a dictionary that maps the values '10', '11', '12' to 1; '13','14' to 2; '20','21','22','24' to 3, so if I typedicc['10'] I get 1, if I typedicc['22'] I get 3. Obviously, the actual DataFrame is quite bigger and I can't do it manually.


You can do it like this:

import pandas as pd  data = [[['10', '11', '12'], 1],         [['13', '14'], 2],         [['20', '21', '22', '24'], 3]]  df = pd.DataFrame(data=data, columns=['rules', 'procedure'])  d = {r : p for rs, p in df[['rules', 'procedure']].values for r in rs} print(d) 


{'20': 3, '10': 1, '11': 1, '24': 3, '14': 2, '22': 3, '13': 2, '12': 1, '21': 3} 


  • The code {r : p for rs, p in df[['rules', 'procedure']].values for r in rs} is a dictionary comprehension, the dictionary counterpart of list.
  • The df[['rules', 'procedure']].values is equivalent to zip(df.rules, df.procedure) it outputs a pair of list, int. So the rs variable is a list and p is an integer.
  • Finally you iterate over the values of rs using the second for loop


As suggested for @piRSquared you can use zip:

d = {r : p for rs, p in zip(df.rules, df.procedure) for r in rs} 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: