簡體   English   中英

將 Python 字典寫入 CSV,其中鍵 = 列,值 = 行

[英]Write Python dictionary to CSV where where keys= columns, values = rows

我有一個字典列表,我希望能夠在 Excel 中打開並正確格式化。 這是我到目前為止所擁有的,使用 csv:

list_of_dicts = [{'hello': 'goodbye'}, {'yes': 'no'}]
out_path= "/docs/outfile.txt"
out_file = open(ipath, 'wb')

writer = csv.writer(ofile, dialect = 'excel')

for items in list_of_dicts:
    for k,v in items.items():
        writer.writerow([k,v])

顯然,當我在 Excel 中打開輸出時,它的格式如下:

key  value
key  value

我想要的是這個:

key   key   key

value value value

我無法弄清楚如何做到這一點,因此將不勝感激。 另外,我希望列名是字典鍵,而不是默認的“A、B、C”等。對不起,如果這是愚蠢的。

謝謝

csv 模塊為此提供了一個DictWriter類,在另一個 SO answer 中對此進行了很好的介紹。 關鍵點是在實例化 DictWriter 時需要知道所有列標題。 您可以從 list_of_dicts 構建字段名稱列表,如果是這樣,您的代碼將變為

list_of_dicts = [{'hello': 'goodbye'}, {'yes': 'no'}]
out_path= "/docs/outfile.txt"
out_file = open(out_path, 'wb')

fieldnames = sorted(list(set(k for d in list_of_dicts for k in d)))
writer = csv.DictWriter(out_file, fieldnames=fieldnames, dialect='excel')

writer.writeheader() # Assumes Python >= 2.7
for row in list_of_dicts:
    writer.writerow(row)
out_file.close()

我構建 fieldnames 的方式是掃描整個list_of_dicts ,所以它會隨着大小的增加而變慢。 您應該直接從數據源構建fieldnames ,例如,如果數據源也是 csv 文件,您可以使用 DictReader 並使用fieldnames = reader.fieldnames

您還可以使用對writer.writerows(list_of_dicts)的單個調用替換for循環並使用with塊來處理文件關閉,在這種情況下,您的代碼將變為

list_of_dicts = [{'hello': 'goodbye'}, {'yes': 'no'}]
out_path= "/docs/outfile.txt"

fieldnames = sorted(list(set(k for d in list_of_dicts for k in d)))

with open(out_path, 'wb') as out_file:
    writer = csv.DictWriter(out_file, fieldnames=fieldnames, dialect='excel')
    writer.writeheader()
    writer.writerows(list_of_dicts)

您需要編寫 2 個單獨的行,一個是鍵,一個是值,而不是:

writer = csv.writer(ofile, dialect = 'excel')

writer.writerow([k for d in list_of_dicts k in d])
writer.writerow([v for d in list_of_dicts v in d.itervalues()])

這兩個列表推導式首先從輸入列表中的字典中提取所有鍵,然后提取所有值,將它們組合成一個列表以寫入 CSV 文件。

我認為最有用的是逐列寫入,因此每個鍵都是一列(適合以后進行數據處理並用於例如 ML)。

昨天我在弄清楚它時遇到了一些麻煩,但我想出了我在其他網站上看到的解決方案。 但是,從我看來,不可能一次瀏覽整個字典,我們必須將其划分為較小的字典(我的 csv 文件最后有 20k 行 - 被調查的人,他們的數據和答案。我這樣做了這個:

    # writing dict to csv
    # 'cleaned' is a name of the output file 
    
    # 1 header 
    # fildnames is going to be columns names 
    
    # 2 create writer 
    writer = csv.DictWriter(cleaned, d.keys())
    
    # 3 attach header 
    writer.writeheader()
    
    # write separate dictionarties 
    for i in range(len(list(d.values())[0])):
        
        writer.writerow({key:d[key][i] for key in d.keys()}) 

我看到我的解決方案還有一個 for 循環,但另一方面,我認為它需要更少的內存(但是,我不確定!!)希望它可以幫助某人;)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM