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