2017-03-01 84 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,