2017-02-14 128 views
0

我試圖從我的Python字典中獲取一個csv。我可以創建一個csv文件並將其放入其中。問題是,當我用excel打開文件頭並且值在一列中。我需要每個鍵和值在一個單獨的列中。例如Python字典到csv excel

 column1 column2 column3  column4 
row 1 "name" "temp" "tempeinheit" "Druck" 
row 2 "test" 24  "C"    0.1 

這是以下代碼。

dict= [{"name" : "test", "temp" : 24, "tempeinheit": "C", "druck" : 0.1, "druckeinheit": "Pa"},{"name" : "benni", "temp" : 24, "tempeinheit": "C", "druck" : 0.1, "druckeinheit": "Pa"}] 
with open("C:\\test#\\test.csv","w",newline='') as csvfile: 

writer = csv.writer(csvfile,dialect="excel-tab") 

for row in dict: 
    if count == 0: 
     header=row.keys() 
     writer.writerow(header) 
     count=+1 
    writer.writerow(row.values()) 

更新:

我只是轉換了字典中2名列表。一個用於鍵和一個用於數據,並用writer.writerow(Data)寫入。另一件事是,我使用Excel 2013和一個新的列它不是delimiter =「,」它的分隔符=「;」。所以 」;」告訴excel將數據放入新列。

感謝您的幫助

+0

你'dict'沒有字典,它的字典 –

+0

也在名單,不命名你的變量'dict' - 你覆蓋標準字典類型 –

+0

YEs我知道這是一個列表。但即使在這種情況下,我想保存它,就像我在我的帖子 – Dieter

回答

0

我試着運行您的代碼,發現以下問題。當您試圖通過代碼來寫它

  • 導入CSV錯誤
  • 文件被關閉。
  • count變量未初始化。

我在這裏添加了我的工作代碼。如果您遇到任何問題,請讓我知道。

import csv 
dict= [{"name" : "test", "temp" : 24, "tempeinheit": "C", "druck" : 0.1, "druckeinheit": "Pa"}, 
    {"name" : "benni", "temp" : 24, "tempeinheit": "C", "druck" : 0}] 
with open("try.csv","a") as csvfile: 
    writer = csv.writer(csvfile,dialect="excel-tab") 
    count = 0 
    for row in dict: 
     if count == 0: 
      header=row.keys() 
      writer.writerow(header) 
      count=+1 
     writer.writerow(row.values()) 
+0

嗨,謝謝,但計數初始化只是一個複製粘貼錯誤,該文件與我的c:\\ try.csv一起工作。並進口,我忘了張貼它,爲此。 – Dieter

0

你可以嘗試像這樣與熊貓:

import pandas as pd 

d = [{"name" : "test", "temp" : 24, "tempeinheit": "C", "druck" : 0.1, "druckeinheit": "Pa"}, 
    {"name" : "benni", "temp" : 24, "tempeinheit": "C", "druck" : 0.1, "druckeinheit": "Pa"}] 

df = pd.DataFrame(d) 

df = df[['name', 'temp', 'tempeinheit', 'druck','druckeinheit']] 
df.to_csv('filename') 
+0

它不工作,像我的代碼一樣的輸出。 – Dieter