首頁  >  文章  >  後端開發  >  如何將 Python 字典寫入 CSV 文件,其中鍵和值位於單獨的行中?

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

Barbara Streisand
Barbara Streisand原創
2024-10-17 18:48:31125瀏覽

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn