Skip to content
Advertisement

Python import csv to dict

Excuse me. I am a noob I saw Python import csv to list Pandas #2

if I have this csv

country    population      population_time    EUR
Germany    82521653.0      2016-12-01         True
France     66991000.0      2017-01-01         True
Indonesia  255461700.0     2017-01-01         False
Ireland    4761865.0       NaT                True
Spain      46549045.0      2017-06-01         True
Vatican    NaN             NaT                True

How to change like this

[{'country': 'Germany', 'population': 82521653.0, 'population_time': Timestamp('2016-12-0100:00:00'), 'EUR': True},
{'country': 'France', 'population': 66991000.0, 'population_time': Timestamp('2017-01-01 00:00:00'), 'EUR': True},
{'country': 'Indonesia', 'population': 255461700.0, 'population_time': Timestamp('2017-01-01 00:00:00'), 'EUR': False},
{'country': 'Ireland', 'population': 4761865.0, 'population_time': NaT, 'EUR': True},
{'country': 'Spain', 'population': 46549045.0, 'population_time': Timestamp('2017-06-01 00:00:00'), 'EUR': True},
{'country': 'Vatican', 'population': nan, 'population_time': NaT, 'EUR': True}]

I just can do like this

import pandas as pd
df = pd.read_csv('file.csv')
print(df.to_dict())

result:

{'country':{0:'Germany', 1:'France', 2:'Indonesia', 3:'Ireland', 4:'Spain', 5:'Vatican'},
 'population ':{0:'82521653.0', 1:'66991000.0', 2:'255461700.0', 3:'4761865.0', 4:'46549045.0', 5:'NaN'},
 'population_time':{0:'2016-12-01', 1:'2017-01-01', 2:'2017-01-01', 3:'NaT', 4:'2017-06-01', 5:'NaT'},
 'EUR':{0:'True', 1:'True', 2:'False', 3:'True', 4:'True', 5:'True'},

Advertisement

Answer

Almost there. Little change to your code. Notice the keyword argument ‘orient’.

import pandas as pd
df = pd.read_csv('file.csv')
print(df.to_dict(orient='records'))

It gives the following output

[{'country': 'Germany', 'population': 82521653.0, 'opulation_time': '2016-12-01', 'EUR': True}, {'country': 'France', 'population': 66991000.0, 'opulation_time': '2017-01-01', 'EUR': True}, {'country': 'Indonesia', 'population': 255461700.0, 'opulation_time': ' 2017-01-01', 'EUR': False}, {'country': 'Ireland', 'population': 4761865.0, 'opulation_time': 'NaT', 'EUR': True}, {'country': 'Spain', 'population': 46549045.0, 'opulation_time': '2017-06-01', 'EUR': True}, {'country': 'Vatican', 'population': nan, 'opulation_time': 'NaT', 'EUR': True}]
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement