我正在尝试将多个字典写入csv文件,其中header(key)只写入一次,而行(值)则根据键写入。我能够为两个字典弄清楚这一点,但是如果我要获得需要编写的多个字典呢?
我正在发送转换为json的推文,所以我试图以每个JSON键排序的CSV文件结束。以下是我正在尝试做的更详细的解释(Writing multiple JSON to CSV in Python - Dictionary to CSV 这是我想要最终得到的,但有数千个潜在的数据行(如果可能,最好按键排序):
这是我的两个词典的基本代码:
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。 我是个傻瓜!
答案 0 :(得分:2)
您可以将多个dicts放在列表中。然后迭代该列表,只写入密钥匹配的行。像这样:
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)