简体   繁体   English

将嵌套字典写入csv python

[英]Writing a nested dictionary into csv python

I am trying to write a nested dictionary into python. 我正在尝试将嵌套字典写入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

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

If you are open to using a 3rd party library, you can use pandas : 如果您愿意使用第三方库,则可以使用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

You can shorten your code by using zip : 您可以使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM