[英]Python dictionary to csv excel
我嘗試從python中的字典中獲取csv。
我可以創建一個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 =“,”但是delimiter =“;”。 所以 ”;” 告訴excel將數據放入新列。
謝謝您的幫助。
我嘗試運行您的代碼,發現以下問題。
我在這里添加了我的工作代碼。 如果您遇到任何問題,請告訴我。
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())
您可以嘗試使用pandas:
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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.