How to Write Python Dictionary to CSV as Header and Value Using csv.DictWriter?

Patricia Arquette
Release: 2024-10-17 18:55:30
Original
290 people have browsed it

How to Write Python Dictionary to CSV as Header and Value Using csv.DictWriter?

csv.DictWriter for CSV File with Headers and Values

This question seeks a method to export a Python dictionary to a CSV file, with the dictionary keys forming the header row and the values comprising the following row.

The provided code snippet:

<code class="python">f = open('mycsvfile.csv','wb')
w = csv.DictWriter(f,my_dict.keys())
w.writerows(my_dict)
f.close()</code>
Copy after login

encounters an issue where only the dictionary keys are written to the first line, leaving the values unwritten in the intended second line.

The solution lies in two adjustments:

  • Utilize DictWriter.writerow() instead of DictWriter.writerows(), as the latter expects a list of dictionaries rather than a single dictionary.
  • Incorporate DictWriter.writeheader() to write the dictionary keys as the header.

Additionally, it is recommended to employ the with statement for file handling, as it streamlines code readability and automatically handles file closing.

Here's an amended code sample that embodies these modifications:

<code class="python">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)</code>
Copy after login

This refined code produces a CSV file with the expected format:

test,testing
1,2
Copy after login

The above is the detailed content of How to Write Python Dictionary to CSV as Header and Value Using csv.DictWriter?. 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!