Convert pandas data frame to a dictionary with row elements as primary key and dict as value

Viewed 139

I'm working in python3. I have a pandas data frame, and I would like to convert it to a dict.

The data frame looks like this:

    ID   year  country
0   123   2019  USA
1   456   2019  UK
2   789   2018  Sweden

I would like to end up with a dict, where the ID number is the primary key and the value is a dict. 'year' and 'country' should be the keys of the 'sub'-dicts.

The output should be like this:

{'123': {'year': 2019, 'country': 'USA'} , '456': {'year': 2019, 'country': 'UK'}, '789': {'year': 2018,  'country' : 'Sweden'}}

What is the fastest and best way to do this? It's a quite large dataframe. Is there any way to do it with .to_dict? Thank you in advance.

0 Answers
Related