簡體   English   中英

將具有多個鍵的 Python 字典寫入 CSV

[英]Writing Python Dictionary with multiple keys to CSV

如圖所示,如何垂直編寫具有多個鍵的字典到 csv? 我只能使用 csv 等原生包。 我得到這個 output我需要這個 output

在它下面的片段(嘗試了不同的循環技術)但似乎沒有用!

import csv

my_file = open("test.csv", mode="w")
sorted_keys = sorted(csv_dict)

writer = csv.DictWriter(my_file, fieldnames = sorted_keys, restval='')
writer.writeheader()
writer.writerow(csv_dict)

回答我自己的問題,但這個片段有效

csv_file = 'file.csv'
with open(csv_file, 'wb') as fd:
writer = csv.writer(fd, delimiter=',')

keys = sorted(dictionary) 
# Format headers for aesthetics
headers = [' {} '.format(key) for key in keys]
writer.writerow(headers)

# Format data to create convenient csv format
csv_data = itertools.izip_longest(*(dictionary[key] for key in keys),
                                  fillvalue='     ')
writer.writerows(csv_data)

暫無
暫無

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

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