Python 将字典列表与每本字典一起写入CSV';在新列中设置值

Python 将字典列表与每本字典一起写入CSV';在新列中设置值,python,excel,csv,dictionary,Python,Excel,Csv,Dictionary,原谅我。我对Python非常陌生 我有一个字典列表,我想写一个Excel电子表格。我确切地知道每本字典将包含多少个键,并且每本字典将具有相同的键。无论我有多少字典,我都希望得到A列中的键和B列中的值。到目前为止,我的代码是: for each in stock_data: with open('output.csv', 'wb') as output: writer = csv.writer(output) for key, value in each.i

原谅我。我对Python非常陌生

我有一个字典列表,我想写一个Excel电子表格。我确切地知道每本字典将包含多少个键,并且每本字典将具有相同的键。无论我有多少字典,我都希望得到A列中的键和B列中的值。到目前为止,我的代码是:

for each in stock_data:
    with open('output.csv', 'wb') as output:
        writer = csv.writer(output)
        for key, value in each.iteritems():
            writer.writerow([key, value])
但是,每次迭代都会覆盖上一次迭代。提前感谢你的帮助

编辑:在那些花时间回答问题的人的帮助下,我得出了以下结论(字典的值是元组):


您希望将循环放在open语句中,这样就不会在每次迭代中关闭和打开文件:

with open('output.csv', 'wb') as output:
    writer = csv.writer(output)
    for each in stock_data:
        for key, value in each.iteritems():
            writer.writerow([key, value])

您最初的
for
循环每次都以
w
打开文件,从而覆盖数据。尝试使用
a
进行追加

要解决修改后的问题,首先列出一张包含所有口述的清单

list_of_dicts = [{'a': 0.26677069056418323, 'b': 0.8343139335624713, 'c': 0.93725104506273127, 'd': 0.12143573904160743, 'e': 0.98963812790339856},
 {'a': 0.40332934706524204, 'b': 0.12289641894313152, 'c': 0.15252859039025357, 'd': 0.24458514688306432, 'e': 0.97469243562553942},
 {'a': 0.1878765127021168, 'b': 0.81273464692942443, 'c': 0.90229778310411091, 'd': 0.6172062385825835, 'e': 0.32644941601058663}]
for key in list_of_dicts[0]: #this iterates through all the keys
    #makes a row using the same key for each dict in the list
    row = [d[key] for d in list_of_dicts] 
    writer.writerow(row)
或者,您可以将其作为一行程序:

writer.writerows(([d[k] for d in list_of_dicts] for k in d))

谢谢显然,这也有助于加快速度。有没有办法让输出将每个新字典的值添加到与前一个字典相同的行上的新列?
writer.writerows(([d[k] for d in list_of_dicts] for k in d))