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 a list inside the dictionary in python

I have a data frame like below. I want to get a dictionary consisting of a list.My expected output is. Can you pls assist me to get it?
enter image description here

enter image description here

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

>Solution :

You can use the handy groupby function in Pandas:

df = pd.DataFrame({
    'Department': ['y1', 'y1', 'y1', 'y2', 'y2', 'y2'], 
    'Section': ['A', 'B', 'C', 'A', 'B', 'C'], 
    'Cost': [10, 20, 30, 40, 50, 60]
})

output = {dept: group['Cost'].tolist() for dept, group in df.groupby('Department')}

gives

{'y1': [10, 20, 30], 'y2': [40, 50, 60]}
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