如何將 Python 字典寫入 CSV 文件,其中鍵和值位於單獨的行中?

Barbara Streisand
發布: 2024-10-17 18:48:31
原創
208 人瀏覽過

How to Write a Python Dictionary to a CSV File with Keys and Values in Separate Rows?

Writing Python Dictionaries to CSV Files

If you need to write a Python dictionary to a csv file, where the dictionary keys appear in the first row and the key values in the second, employ the following approach:

Step 1: Use DictWriter.writerow()

The code you cited uses DictWriter.writerows() which expects a list of dictionaries, not a single dictionary. To write a single row, utilize DictWriter.writerow():

import csv

my_dict = {"test": 1, "testing": 2}

with open("mycsvfile.csv", "w", newline="") as f:
    w = csv.DictWriter(f, my_dict.keys())
    w.writeheader()
    w.writerow(my_dict)
登入後複製

Step 2: Include DictWriter.writeheader()

If you desire a header row for your CSV file, call DictWriter.writeheader() before writing the dictionary:

    w.writeheader()
    w.writerow(my_dict)
登入後複製

Step 3: Utilize the "with" Statement

The "with" statement handles file opening and closing elegantly, even during exceptions:

with open("mycsvfile.csv", "w", newline="") as f:
    # ...
登入後複製
登入後複製

Step 4: Disable Newline Management

The CSV writer manages line breaks internally, so disable the default behavior in open() using newline="":

with open("mycsvfile.csv", "w", newline="") as f:
    # ...
登入後複製
登入後複製

This revised code generates a CSV file with the dictionary keys and values correctly separated:

test,testing
1,2
登入後複製

以上是如何將 Python 字典寫入 CSV 文件,其中鍵和值位於單獨的行中?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板