Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dataframe to nested dictionary

I have a dataframe with 3 columns "ID" , "Date" , "House_Price_Index" and I want to convert this into a dictionary looking like:

{ID:{"Date":"Value" , "House_Price_Index":"Value"}}

Here’s a sample of the dataframe:

ID      Date  House_Price_Index
0      1/1/1975            61.0900
1      1/1/1976            65.5250
2      1/1/1977            73.4350
3      1/1/1978            83.7450
4      1/1/1979            95.1325
5      1/1/1980           102.6675

So the output should be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{0:{"Date":"1/1/1975","House_Price_Index":"61.0900"}}

… so on and so forth

Thank you very much!

>Solution :

Use DataFrame.to_dict with convert ID to index (because column):

d = df.set_index('ID').to_dict('index')
print (d)
{0: {'Date': '1/1/1975', 'House_Price_Index': 61.09}, 
 1: {'Date': '1/1/1976', 'House_Price_Index': 65.525},
 2: {'Date': '1/1/1977', 'House_Price_Index': 73.435},
 3: {'Date': '1/1/1978', 'House_Price_Index': 83.745},
 4: {'Date': '1/1/1979', 'House_Price_Index': 95.1325},
 5: {'Date': '1/1/1980', 'House_Price_Index': 102.6675}}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading