![](/img/trans.png)
[英]python; merge dictionaries with each dictionary in a new column of the output csv file
[英]Writing list of dictionaries to CSV with each dictionary's values in a new column
原谅我。 我是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])
但是,每次迭代都会覆盖前一个。 在此先感谢您的帮助。
编辑:在花时间回答的那些人的帮助下,我最终得到了这一点(字典的值是元组):
with open('output.csv', 'wb') as output:
fieldnames = ['Volume', 'Symbol', 'Adj_Close', 'High', 'Low', 'Date', 'Close', 'Open']
writer = csv.DictWriter(output, fieldnames=fieldnames)
writer.writeheader()
writer = csv.writer(output)
for each in stock_data:
temp_list = []
for value in each.iteritems():
value = list(value)
temp_list.append(value[1])
writer.writerow(temp_list)
您想将循环放入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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.