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

How to convert dataframe columns into a dictionary with one key and multiple value without tuples?

I got a large dataframe like that, which basically looks like this:

Name km Min Max
test 24.6 43 555
test 63.9 31 666

which I would like to turn into a dictionary like:

{24.6: ["test",43,555],
63.9: ["test",31,666]}

What I found so far was https://stackoverflow.com/a/67496211/9218349, which would result in:

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

dict(zip(zip(df.km),zip(df.Name, df.Min,df.Max)))

this way i receive a dictionary of tuples, but I wont the keys to be floats and the values to be strings and floats. The floats should generally have 2 decimal places.

How would I do that?

>Solution :

Use to_dict('list') on the transposed DataFrame:

df.set_index('km').T.to_dict('list')

output:

{24.6: ['test', 43, 555], 63.9: ['test', 31, 666]}

NB. note that in case you have duplicated values in "km", as you can only have unique keys in a dictionary, only the latest row will be kept

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