[英]Python: Writing to a csv file from a 'list' of {(tuples): value} dicts
Greetings All. 大家问候。
I have a [(tuple): value] dicts as elements in a list as follows: 我有一个[(tuple):value]字典作为列表中的元素,如下所示:
lst = [{('unit1', 'test1'): 11, ('unit1','test2'): 12}, {('unit2','test1'): 13, ('unit2','test2'):14 }]
testnames = ['test1','test2']
unitnames = ['unit1','unit2']
How to write to csv file with the following output? 如何使用以下输出写入csv文件?
unitnames, test1, test2 单位名称,test1,test2
unit1, 11, 12 1、11、12单元
unit2, 13, 14 unit2,13,14
Thanks. 谢谢。
First, flatten the structure. 首先,将结构弄平。
units = collections.defaultdict(lambda: collections.defaultdict(lambda: float('-inf')))
for (u, t), r in lst.iteritems():
units[u][t] = r
table = [(u, t['test1'], t['test2']) for (u, t) in units.iteritems()]
Following code creates a dict that can be dumped to a csv: 以下代码创建了一个可以转储到csv的字典:
from collections import defaultdict
d = defaultdict(list)
for (unit, test), val in lst.items():
d[unit].append(val)
The way you have lst grouped is redundant; 您第一次分组的方式是多余的; all keys are unique, it might as well be a single dictionary, as
所有键都是唯一的,也可能是一个字典,例如
data = {
('unit1', 'test1'): 11,
('unit1', 'test2'): 12,
('unit2', 'test1'): 13,
('unit2', 'test2'): 14
}
then 然后
import csv
def getUniqueValues(seq):
"Return sorted list of unique values in sequence"
values = list(set(seq))
values.sort()
return values
def dataArray(data2d, rowIterField=0, rowLabel='', defaultVal=''):
# get all unique unit and test labels
rowLabels = getUniqueValues(key[rowIterField] for key in data2d)
colLabels = getUniqueValues(key[1-rowIterField] for key in data2d)
# create key-tuple maker
if rowIterField==0:
key = lambda row,col: (row, col)
else:
key = lambda row,col: (col, row)
# header row
yield [rowLabel] + colLabels
for row in rowLabels:
# data rows
yield [row] + [data2d.get(key(row,col), defaultVal) for col in colLabels]
def main():
with open('output.csv', 'wb') as outf:
outcsv = csv.writer(outf)
outcsv.writerows(dataArray(data, 0, 'unitnames'))
if __name__=="__main__":
main()
and the output can easily be flipped (units across, tests down) by changing dataArray(data, 0, 'unitnames')
to dataArray(data, 1, 'testnames')
. 通过将
dataArray(data, 0, 'unitnames')
更改为dataArray(data, 1, 'testnames')
可以轻松翻转输出(跨单元,向下测试dataArray(data, 1, 'testnames')
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.