user308827
user308827

Reputation: 21961

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'}

Upvotes: 4

Views: 23824

Answers (2)

Leb
Leb

Reputation: 15953

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}

Upvotes: 5

Alexander
Alexander

Reputation: 109536

dt = pandas.read_csv('file.csv', index_col=1, skiprows=1).T.to_dict()

Upvotes: 14

Related Questions