python列表写入字典,将多个字典写入CSV,并使用Python的一个标题

I am trying to write multiple dictionaries to a csv file, where header (key) gets written only once and rows (values) are written based on the key. I was able to figure this out for two dictionaries, but what if I am getting multiple dictionaries that need to be written?

I am streaming tweets which get converted to json, so I am trying to end with a CSV file that is sorted by each JSON key. Here is a more detailed explanation of what I am trying to do (Writing multiple JSON to CSV in Python - Dictionary to CSV

Here is what I am trying to end up with but with thousands of potential rows of data (preferably sorted by key if possible):

QQU1m.png

Here is my basic code for two dictionaries:

import csv

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4', 'key5': 'value5', 'key6': 'value6', 'key7': 'value7'}

my_dict2 = {'key1': 'value1A', 'key2': 'value2A', 'key3': 'value3A', 'key4': 'value4A', 'key5': 'value5A', 'key6': 'value6A', 'key7': 'value7A'}

with open('mycsvfile.csv', 'wb') as f:

w = csv.DictWriter(f, my_dict.keys())

w.writeheader()

w.writerow(my_dict)

if my_dict.keys() == my_dict2.keys():

w.writerow(my_dict2)

print my_dict

P.S.

I am a begginer!

解决方案

You can put the multiple dicts in a list. You then iterate over that list and only write the rows where the keys match. Something like this:

keys = ['key1', 'key2', 'key3', 'key4', 'key5'] # and so forth..

dictionaries = [my_dict, my_dict2] # Just an example, you probably build this list while you stream the tweets.

with open('mycsvfile.csv', 'wb') as f:

w = csv.DictWriter(f, my_dict.keys())

w.writeheader()

for d in [x for x in dictionaries if x.keys() == keys]: # only matching keys.

w.writerow(d)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值