Home  >  Article  >  Backend Development  >  How to Write Python Dictionary to CSV as Header and Value Using csv.DictWriter?

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

Patricia Arquette
Patricia ArquetteOriginal
2024-10-17 18:55:30382browse

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>

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>

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

test,testing
1,2

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!

Statement:
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