Home > Mobile >  Make use of 3 dataframe columns to create a dictionary with Col1 as Key and a dictionary of (Col2 an
Make use of 3 dataframe columns to create a dictionary with Col1 as Key and a dictionary of (Col2 an

Time:02-27

everyone. I really need some help regarding a dictionary that I want to create using the following dataframe (as an example).

Column1 Column2 Integer
Apple Orange 5
Apple Pineapple 10
Apple Juice 3
Strawberry Raspberry 11

I want this dataframe be converted into a dictionary like that:

  • first column to be a key with a dictionary as value (with column2 as key and integer as value)

The output should be:

dictionary = {
'Apple': {'Orange': 5, 'Pineapple': 10, 'Juice': 3}
'Strawberry': {'Raspberry': 11}
}

CodePudding user response:

Group the dataframe by Column1 and create key value pairs inside a dict comprehension

{k: dict(zip(g['Column2'], g['Integer'])) for k, g in df.groupby('Column1')}

{'Apple': {'Juice': 3, 'Orange': 5, 'Pineapple': 10},
 'Strawberry': {'Raspberry': 11}}
  • Related