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

Use pandas to create dict out of CSV columns

I have a csv file(with single line) like this

drop1,drop2,key1,value1,key2,value2,key3,value3...keyN,valueN

The output I need is

{
'key1':'value1',
'key2':'value2',
..
'keyN':'valueN',
}

I intend to use dataframes to do.
I tried using reshape and pivot, but being new to pandas, I am not able to figure it out.

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

Any pointer will be great help .

>Solution :

You can try reshape the values after first two columns to shape (-1, 2) where first column is key and second column is value

df = pd.read_csv('your.csv', header=None)
out = (pd.DataFrame(df.iloc[:, 2:].values.reshape(-1, 2))
       .set_index(0)[1].to_dict())
print(df)

       0      1     2       3     4       5     6       7     8       9
0  drop1  drop2  key1  value1  key2  value2  key3  value3  keyN  valueN

print(out)

{'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'keyN': 'valueN'}
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