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

Converting a PD DF to a dictionary

I have a pd dataframe as seen in image:
image of data

imported via the pd.read_csv method.

I would like to convert it to a dictionary, where the key is ‘Countries’, and the value is a list of the numbers 1 to 300.
How is the best way to do this? I have tried other methods listed on stack but since my df doesn’t have column headings it is not working

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 :

Something like this should do what your question asks:

d = {row[1]:list(row[2:]) for row in df.itertuples()}

Here is sample code showing the above in the context of your question:

records = [
    ['afghanistan', -0.9,-0.7,-0.5,-0.3,-0.1,0.1,0.3,0.5,0.7,0.9],
    ['albania', -0.9,-0.7,-0.5,-0.3,-0.1,0.1,0.3,0.5,0.7,0.9],
    ['algeria', -0.9,-0.7,-0.5,-0.3,-0.1,0.1,0.3,0.5,0.7,0.9],
    ['andorra', -0.9,-0.7,-0.5,-0.3,-0.1,0.1,0.3,0.5,0.7,0.9]
]

import pandas as pd
df = pd.DataFrame(records)
print(df)

d = {row[1]:list(row[2:]) for row in df.itertuples()}
print()
[print(f"{k} : {v}") for k, v in d.items()]

Output:

            0    1    2    3    4    5    6    7    8    9    10
0  afghanistan -0.9 -0.7 -0.5 -0.3 -0.1  0.1  0.3  0.5  0.7  0.9
1      albania -0.9 -0.7 -0.5 -0.3 -0.1  0.1  0.3  0.5  0.7  0.9
2      algeria -0.9 -0.7 -0.5 -0.3 -0.1  0.1  0.3  0.5  0.7  0.9
3      andorra -0.9 -0.7 -0.5 -0.3 -0.1  0.1  0.3  0.5  0.7  0.9

afghanistan : [-0.9, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.7, 0.9]
albania : [-0.9, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.7, 0.9]
algeria : [-0.9, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.7, 0.9]
andorra : [-0.9, -0.7, -0.5, -0.3, -0.1, 0.1, 0.3, 0.5, 0.7, 0.9]
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