- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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")
Advertisements