我正在尝试编写一个函数,它使用以下格式的字典将它们写入一个csv文件,该文件具有每个测试(第一个字典中的键)的列以及不同污染物的行在子词典中的键)正在被测试和。每个单元格将包含子字典的值。更改字典格式
output=table.csv
dictionaryEx={'run2.csv': {' ph': 25, ' escherichia coli': 14, ' enterococci': 1},
'run1.csv': { ' enterococci': 7, ' ph': 160, ' nickel': 3,
' dieldrin': 4, ' barium': 1, ' trichloroethylene': 1, }
def writeFile(dictionary)
with open(output,'w') as outputFile:
polDict={}
for element in dictionary:
print element
for pollutant,value in element.values():
polDict[pollutant]={element:value}
for element in polDict:
outputFile.write(pollutant+','+ polDict.values())
outputFile.close()
现在,我试图做一个新的字典来做到这一点,但我要的问题与它写在运行。另一个数据结构会更好地工作吗? 的CSV应该如何看
“”,run2.csv,run1.csv \ n pH值,25160 \ n大肠杆菌,14 “” \ n肠球菌,1,7 \ n镍 “” 3
你首先应该解决的压痕。你是否在Python IDLE中试过这个例子?您最后也不需要关闭该文件,因为** with open **将为您完成。 – elena
为什么你不使用与'dictionaries'一起工作的'csv'模块就好了(https://docs.python.org/2/library/csv.html#csv.DictWriter)? –
对不起,但你能显示结果csv会是什么样子?有可能,这对于'csv'模块来说非常简单,但最好用你期望的.csv来显式化。 –