Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Make use of 3 dataframe columns to create a dictionary with Col1 as Key and a dictionary of (Col2 and col3) as values for that Col1 key

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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}}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading