+2 votes
in Programming Languages by (73.8k points)

I have a CSV file containing the following data. I want to convert this data into a Python dictionary. The column names should be the keys and rows should be the values of the dictionary. How can I do it?

A   B    C
1  11  111
2  22  222
3  33  333
4  44  444
5  55  555
to
{'A': [1, 2, 3, 4, 5], 'B': [11, 22, 33, 44, 55], 'C': [111, 222, 333, 444, 555]}

1 Answer

+1 vote
by (349k points)
selected by
 
Best answer

There could be several ways to convert a CSV file into a Python dictionary, but using functions of Pandas DataFrame is a Pythonic way in my opinion.

Here is an example to show how to use Pandas Dataframe to convert CSV into a dictionary.

>>> import pandas as pd
>>> df1=pd.read_csv('abc.csv') #read csv file and create a dataframe
>>> df1
   A   B    C
0  1  11  111
1  2  22  222
2  3  33  333
3  4  44  444
4  5  55  555
>>> df1.to_dict(orient='list') #convert dataframe to dictionary
{'A': [1, 2, 3, 4, 5], 'B': [11, 22, 33, 44, 55], 'C': [111, 222, 333, 444, 555]}


...