How to write nested dictionaries to a CSV file

+1 vote

I am facing difficulty in writing a nested dictionary to a CSV file. Below is the dictionary: Score = {'Student-1': {'1st Term': 0, '2nd Term': 0, '3rd Term': 0, '4th Term': 0}, 'ge60le90': {'1st Term': 4, '2nd Term': 0, '3rd Term': 0, '4th Term': 0}, 'gt90': {'1st Term': 0, '2nd Term': 1, '3rd Term': 2, '4th Term': 1} } I want to write this dictionary in a CSV format, consider the below example:

Apr 15, 2018 in Python by ana1504.k
• 7,910 points
26,733 views

4 answers to this question.

+1 vote

You can use Pandas Module, consider the code below:
import pandas as pd

Score = {'Student-1': {'1st Term': 0, '2nd Term': 0, '3rd Term': 0, '4th Term': 0}, 'Student-2': {'1st Term': 4, '2nd Term': 0, '3rd Term': 0, '4th Term': 0}, 'Student-3': {'1st Term': 0, '2nd Term': 1, '3rd Term': 2, '4th Term': 1} }

df = pd.DataFrame(Score)

df = df.rename(columns={'Student-1': 'Good',
'Student-2': 'Medium',
'Student-3': 'Bad'})

df.to_csv('student.csv', index=False)

answered Apr 15, 2018 by anto.trigg4
• 3,440 points
+1 vote
import csv
import itertools
import sys

fields = [ 'org', '2015', '2014', '2013' ]
dw     = { 'orgname1': { '2015' : 2, '2014' : 1, '2013' : 1 },
           'orgname2': { '2015' : 1, '2014' : 2, '2013' : 3 },
           'orgname3': { '2015' : 1, '2014' : 3, '2013' : 1 }
        }

w = csv.DictWriter( sys.stdout, fields )
for key,val in sorted(dw.items()):
    row = {'org': key}
    row.update(val)
    w.writerow(row)
answered Oct 18, 2018 by Roshan
+1 vote
import csv
import itertools

fields = [ 'org', '2015', '2014', '2013' ]
dw     = { 'orgname1': { '2015' : 2, '2014' : 1, '2013' : 1 },
           'orgname2': { '2015' : 1, '2014' : 2, '2013' : 3 },
           'orgname3': { '2015' : 1, '2014' : 3, '2013' : 1 }
        }

with open("test_output.csv", "wb") as f:
    w = csv.DictWriter(f, fields)
    w.writeheader()
    for k in dw:
        w.writerow({field: dw[k].get(field) or k for field in fields})

Output:

org,2015,2014,2013
orgname1,2,1,1
orgname3,1,3,1
orgname2,1,2,3
answered Oct 18, 2018 by helena

If the value is 0 it is replacing the value 0 with the 'org' value.

Use this data set to test it:

dw     = { 'orgname1': { '2015' : 0, '2014' : 0, '2013' : 1 },
           'orgname2': { '2015' : 1, '2014' : 0, '2013' : 3 },
           'orgname3': { '2015' : 1, '2014' : 3, '2013' : 1 }
        }
+1 vote

Using DictWriter there is no need in sorting the fields in advance, since w.writerow() will assure the correct order. But it does make sense to sort the items themselves.

So putting together all the above suggestions and picking the best of each, i would come up with following code:

import csv
import itertools

def mergedict(a,b):
    a.update(b)
    return a

fields = [ 'org', '2015', '2014', '2013' ]
dw     = { 'orgname1': { '2015' : 2, '2014' : 1, '2013' : 1 },
           'orgname2': { '2015' : 1, '2014' : 2, '2013' : 3 },
           'orgname3': { '2015' : 1, '2014' : 3, '2013' : 1 }
        }

with open("test_output.csv", "wb") as f:
    w = csv.DictWriter( f, fields )
    w.writeheader()
    for k,d in sorted(dw.items()):
        w.writerow(mergedict({'org': k},d))
answered Oct 18, 2018 by Richard William

Related Questions In Python

0 votes
1 answer

How can I write nested dictionaries to a csv file?

You can use the pandas library to ...READ MORE

answered Apr 17, 2018 in Python by anonymous
913 views
–1 vote
2 answers
0 votes
1 answer

How to write data to a file in Python?

Refer to the below code. data=’whatever your data ...READ MORE

answered May 13, 2019 in Python by Shaam
683 views
0 votes
1 answer

How to find the value of a row in a csv file in python?

If you want to find the value ...READ MORE

answered May 20, 2019 in Python by Sanam
18,505 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,023 views
0 votes
1 answer
+2 votes
2 answers

How can I create a new file in Python?

You can try the below code which ...READ MORE

answered Mar 31, 2018 in Python by anto.trigg4
• 3,440 points
958 views
+4 votes
7 answers
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP