2017-03-01 83 views
0

我正在尝试编写一个函数,它使用以下格式的字典将它们写入一个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

enter image description here

+1

你首先应该解决的压痕。你是否在Python IDLE中试过这个例子?您最后也不需要关闭该文件,因为** with open **将为您完成。 – elena

+1

为什么你不使用与'dictionaries'一起工作的'csv'模块就好了(https://docs.python.org/2/library/csv.html#csv.DictWriter)? –

+0

对不起,但你能显示结果csv会是什么样子?有可能,这对于'csv'模块来说非常简单,但最好用你期望的.csv来显式化。 –

回答

0

相似,但较短的

cols = dictionaryEx.keys() 
rows = set() 
for v in dictionaryEx.values(): 
    rows.update(v.keys() 

with open('outputfile','w') as file: 
    file.write(',' + ','.join(cols) + '\n') 
    for r in sorted(rows): 
     file.write(r + ",") 
     file.write(",".join([str(d,get(r,"")) for d in dictionaryEx.values()])) 
     file.write("\n") 

应该得到这个输出文件

,run2.csv,run1.csv 
barium,,1 
dieldrin,,4 
enterococci,1,7 
escherichia coli,14, 
nickel,,3 
ph,25,160 
trichloroethylene,,1 
0

这个版本对我的作品与Python 3.5.1:

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: 
     # Write the title line. 
     outputFile.write(",") 
     for key in dictionary.keys(): 
      outputFile.write(key + ",") 
     outputFile.write("\n") 

     # Generate a sorted unique list of pollutants. 
     pollutants = [] 
     for d in dictionary.values(): 
      for k in d.keys(): 
       pollutants.append(k) 
     # This sorts the list and removes duplicates. 
     pollutants = sorted(set(pollutants)) 

     # For each possible pollutant, output the pollutant's 
     # value for each CSV. 
     for p in pollutants: 
      outputFile.write(p + ",") 
      for csv in dictionary.keys(): 
       if p in dictionary[csv]: 
        outputFile.write(str(dictionary[csv][p])) 
       outputFile.write(",") 
      outputFile.write("\n") 

writeFile(dictionaryEx) 

这里是输出,这似乎正常,当我在Excel中打开它格式化:

,run2.csv,run1.csv, 
barium,,1, 
dieldrin,,4, 
enterococci,1,7, 
escherichia coli,14,, 
nickel,,3, 
ph,25,160, 
trichloroethylene,,1,