0

I am trying to write a nested dictionary into python. I have a dictionary like below:

{'09-04-2018' : {1: 11, 2: 5, 3: 1, 4: 1, 5: 0} , '10-04-2018' : {1: 5, 2: 1, 3: 1, 4: 1, 5: 0}}

and i wanted to write it something like:

count,09-04-2018,10-04-2018
1,11,5
2,5,1
3,1,1
4,1,1
5,0,0
0

3 Answers 3

2

The following produces the requested output:

data = {'09-04-2018' : {1: 11, 2: 5, 3: 1, 4: 1, 5: 0} , '10-04-2018' : {1: 5, 2: 1, 3: 1, 4: 1, 5: 0}}

rows = []
keys = sorted(data)
header = ['count'] + keys
counts = sorted(set(k for v in data.values() for k in v))
for count in counts:
    l = [count]
    for key in keys:    
        l.append(data[key].get(count))
    rows.append(l)

print header
print rows

import csv
with open('output.csv', 'w') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(header)
    writer.writerows(rows)

This builds up the rows before writing them it is possible to write them directly rather than appending them to the list and writing the contents of the list.

produces this output:

count,09-04-2018,10-04-2018
1,11,5
2,5,1
3,1,1
4,1,1
5,0,0
Sign up to request clarification or add additional context in comments.

Comments

1

If you are open to using a 3rd party library, you can use pandas:

import pandas as pd

d = {'09-04-2018' : {1: 11, 2: 5, 3: 1, 4: 1, 5: 0},
     '10-04-2018' : {1: 5, 2: 1, 3: 1, 4: 1, 5: 0}}

# create dataframe from dictionary
df = pd.DataFrame.from_dict(d).reset_index().rename(columns={'index': 'count'})

# write dataframe to csv file
df.to_csv('file.csv', index=False)

print(df)

#    count  09-04-2018  10-04-2018
# 0      1          11           5
# 1      2           5           1
# 2      3           1           1
# 3      4           1           1
# 4      5           0           0

Comments

0

You can shorten your code by using zip:

import csv
d = {'09-04-2018' : {1: 11, 2: 5, 3: 1, 4: 1, 5: 0} , '10-04-2018' : {1: 5, 2: 1, 3: 1, 4: 1, 5: 0}}
with open('filename.csv', 'w') as f:
  write = csv.writer(f)
  full_rows = [i for h in [zip(*b.items()) for _, b in sorted(d.items(), key=lambda x:map(int, x[0].split('-')))] for i in h]
  write.writerows([['counts']+[a for a, _ in sorted(d.items(), key=lambda x:map(int, x[0].split('-')))]]+list(zip(*[full_rows[0]]+full_rows[1::2])))

Output:

counts,09-04-2018,10-04-2018
1,11,5
2,5,1
3,1,1
4,1,1
5,0,0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.