Valencia
Valencia

Reputation: 15

Nested dictionary to csv excel

I have tried many different approaches to get the below result in excel,

              Monday Tuesday Wednesday Thursday Friday Saturday Sunday
Breakfast     0      0       289       0        265    0         0
Lunch         832    0       0         0        0      0         0
Dinner        201    0       0         0        0      0         620

from the follow dictionary:

 my_dict = {"Monday":{"Breakfast": 0, "Lunch": 832, "Dinner": 201},
       "Tuesday":{"Breakfast": 0, "Lunch": 0, "Dinner": 0},
       "Wednesday":{"Breakfast": 289, "Lunch": 0, "Dinner": 0},
       "Thursday":{"Breakfast": 0, "Lunch": 0, "Dinner": 0},
       "Friday":{"Breakfast": 265, "Lunch": 0, "Dinner": 0},
       "Saturday":{"Breakfast": 0, "Lunch": 0, "Dinner": 0},
       "Sunday":{"Breakfast": 0, "Lunch": 0, "Dinner": 620}}

But I havent be able to get the result I would like. One of the attempts I made that doesnt work is this one:

import csv
import itertools

headings = (d.keys()[0] for d in my_dict)
entries = (sorted(my_dict[index][col].items()) for index, col in 
enumerate(headings))

with open('output.csv', 'wb') as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerow(['items'] + headings)

    for cols in itertools.iziplogest(*entries, fillvalue=['<n/a>']*len(entries[0])):
         csv_output.writerow([cols[0][0]]+[col[1] for col in cols])

I am new to programming and am not yet overly familiar with object orientation, so I would like to find an answer that is as straight-forward as possible. Thanks!

Upvotes: 1

Views: 763

Answers (1)

Satyadev
Satyadev

Reputation: 643

Try using pandas for this!

Install the package if you don't have it already.

pip install pandas 

Then do the following code:

import pandas as pd
df = pd.DataFrame.from_dict(data=my_dict)
df=df[['Monday','Tuesday', 'Wednesday','Thursday','Friday','Saturday','Sunday']]
df.to_csv('output.csv',index=False)

You should get a csv as follows:

Monday Tuesday Wednesday Thursday Friday Saturday Sunday Breakfast 0 0 289 0 265 0 0 Dinner 201 0 0 0 0 0 620 Lunch 832 0 0 0 0 0 0

And that's it , you should have a csv as you require!

Upvotes: 1

Related Questions