Reading csv file as dictionary using pandas
17,990
Solution 1
dt = pandas.read_csv('file.csv', index_col=1, skiprows=1).T.to_dict()
Solution 2
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}
Author by
user308827
Updated on June 13, 2022Comments
-
user308827 about 2 years
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'}