- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to save a Python Dictionary to CSV file?
CSV (Comma Separated Values) is a most common file format that is widely supported by many platforms and applications.
Use csv module from Python's standard library. Easiest way is to open a csv file in 'w' mode with the help of open() function and write key value pair in comma separated form.
import csv my_dict = {'1': 'aaa', '2': 'bbb', '3': 'ccc'} with open('test.csv', 'w') as f: for key in my_dict.keys(): f.write("%s,%s\n"%(key,my_dict[key]))
The csv module contains DictWriter method that requires name of csv file to write and a list object containing field names. The writeheader() method writes first line in csv file as field names. The subsequent for loop writes each row in csv form to the csv file.
import csv csv_columns = ['No','Name','Country'] dict_data = [ {'No': 1, 'Name': 'Alex', 'Country': 'India'}, {'No': 2, 'Name': 'Ben', 'Country': 'USA'}, {'No': 3, 'Name': 'Shri Ram', 'Country': 'India'}, {'No': 4, 'Name': 'Smith', 'Country': 'USA'}, {'No': 5, 'Name': 'Yuva Raj', 'Country': 'India'}, ] csv_file = "Names.csv" try: with open(csv_file, 'w') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=csv_columns) writer.writeheader() for data in dict_data: writer.writerow(data) except IOError: print("I/O error")
- Related Articles
- How to save a vector in R as CSV file?
- How to save a matrix as CSV file using R?
- How to save HTML Tables data to CSV in Python
- How to read CSV file in Python?
- Python - How to write pandas dataframe to a CSV file
- How to create a Python dictionary from text file?
- Python Tkinter – How to export data from Entry Fields to a CSV file?
- How to parse a CSV file using PHP
- How to save a csv and read using fread in R?
- How to convert JSON file to CSV file using PowerShell?
- How to import csv file in PHP?
- How to create a CSV file manually in PowerShell?
- How to create a blank csv file in R?
- Extract csv file specific columns to list in Python
- How to Save Command Output to a File in Linux?

Advertisements