Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading csv file as dictionary using pandas

I have the foll. csv with 1st row as header:

A      B
test    23
try     34

I want to read in this as a dictionary, so doing this:

dt = pandas.read_csv('file.csv').to_dict()

However, this reads in the header row as key. I want the values in column 'A' to be the keys. How do I do that i.e. get answer like this:

{'test':'23', 'try':'34'}
like image 483
user308827 Avatar asked Oct 22 '25 06:10

user308827


2 Answers

dt = pandas.read_csv('file.csv', index_col=1, skiprows=1).T.to_dict()
like image 121
Alexander Avatar answered Oct 23 '25 22:10

Alexander


Duplicating data:

import pandas as pd
from io import StringIO

data="""
A      B
test    23
try     34
"""

df = pd.read_csv(StringIO(data), delimiter='\s+')

Converting to dictioanry:

print(dict(df.values))

Will give:

{'try': 34, 'test': 23}
like image 44
Leb Avatar answered Oct 23 '25 21:10

Leb