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

Barbara Streisand
Release: 2024-10-17 18:48:31
Original
124 people have browsed it

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)
Copy after login

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)
Copy after login

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:
    # ...
Copy after login
Copy after login

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:
    # ...
Copy after login
Copy after login

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

test,testing
1,2
Copy after login

The above is the detailed content of How to Write a Python Dictionary to a CSV File with Keys and Values in Separate Rows?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!