Table of contents
1.
Introduction
2.
Python Dictionary
3.
CSV File
4.
Conversion of Python Dictionary to CSV File
4.1.
Importing Module
4.2.
Creating CSV Columns
4.3.
Creating Python Dictionary
4.4.
Writing Creating Python Dictionary
4.5.
Execution of Code
5.
Frequently Asked Questions
5.1.
What are the applications of Python Dictionary?
5.2.
Where CSV Files can be opened?
5.3.
How the data can be read from a CSV file using Python?
5.4.
How Python Dictionary can be created?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Python Dictionary to CSV file

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

CSV stands for Comma Separated Values, which is a type of file that is widely supported by various applications and platforms such as Spreadsheet Software, Databases, and Web Applications. Dictionary in Python is the data structure where the key-value pair can be stored. Now Python is one of the languages using which we can convert the Python dictionary to CSV files.

Python Dictionary to CSV file

In the article “Python Dictionary to CSV file”, we will discuss about python dictionaries, CSV files, and how a Python dictionary can be converted into a CSV file.

Python Dictionary

In Python, The dictionary is a type of data structure that is used to store the key: value pairs. The dictionary is an ordered, changeable, no-duplicate data structure. Python Dictionary can be used to store any data type such as integer, float, string, object, boolean, etc.

Here is an example of the structure of a Python Dictionary:

dict = {
  "name": "Ninja Coder",
  "isBeginner": True,
  "dob": 2001,
  "hobbies": ["chess", "gym", "books"]
}
You can also try this code with Online Python Compiler
Run Code

 

In the above dictionary, the size of the dictionary is 4, where the first key is a name with the value “Ninja Coder”, which is a string. The second key is isBeginner, whose value is True which is of Boolean data type. The third key is dob, whose value is 2001, which is of Integer data type. The fourth key is hobbies that pair with ["chess", "gym", "books"] whose data type is a list of strings.

There are some of the rules that should be followed while creating a Python dictionary:

  • The key in the dictionary should be a single element.
     
  • The names of keys are case-sensitive, i.e., in either uppercase or lowercase will be treated differently.
     
  • The keys of the dictionary should always be unique, which can only be of immutable data type.
     
  • The values in a dictionary can be of any data type.

CSV File

CSV stands for Comma Separated Values and is a type of file that contains information using commas. CSV files can be opened by the text editors, Notepad or TextEdit. Here is the structure of the CSV file:

csv editor


Now this CSV file can also be opened by Excel or Google Sheets, and here is the structure for the same:

csv excel

Conversion of Python Dictionary to CSV File

In Python, There is a module called csv that can be imported into the Python program. By using the “csv” module, we can write the data in the .csv file. Here are the steps below, which you can follow to convert the Python dictionary to CSV file:

Importing Module

The only module we need to import is the “csv”, which you can do with the following code:

import csv
You can also try this code with Online Python Compiler
Run Code

Creating CSV Columns

As we have seen in the previous section, that csv contains columns and rows. So first, we need to create an array for the columns, which can be done by using the following code:

columns = ['Name', 'Branch', 'Roll No']
You can also try this code with Online Python Compiler
Run Code


In the above code, we created a ‘columns’ array where three columns are created, namely Name, Branch, and Roll No. So CSV File will contain three columns with these names.

Creating Python Dictionary

After creating columns for the CSV file, we need to create the rows for the CSV file, which are nothing but the Python dictionary. In Python Dictionary, each object defines a row for the CSV file. Here is the following code to perform the same:

rows = [
{'Name': 'Ninja 1', 'Branch': 'Computer Science Engineering', 'Roll No': '100'},
{'Name': 'Ninja 2', 'Branch': 'Information Technology', 'Roll No': '101'},
{'Name': 'Ninja 3', 'Branch': 'Electronics and Electrical Engineering', 'Roll No': '102'},
{'Name': 'Ninja 4', 'Branch': 'Civil Engineering', 'Roll No': '103'},
{'Name': 'Ninja 5', 'Branch': 'Mechanical Engineering', 'Roll No': '104'},
{'Name': 'Ninja 6', 'Branch': 'Information Technology', 'Roll No': '105'}
]
You can also try this code with Online Python Compiler
Run Code

 

In the above code, there is a Python dictionary called ‘rows’, which contains five objects (or five rows for the CSV file).

Writing Creating Python Dictionary

Now we are ready with the rows and columns; here comes the main part of the article “Python Dictionary to CSV file”, where the writing of the dictionary data to the CSV file will be done. Here is the following code for the same:

with open('Students.csv', 'w') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames=columns)
    writer.writeheader()
    writer.writerows(rows)
You can also try this code with Online Python Compiler
Run Code

 

In the above code, the “Students.csv” file will be opened using the “open” method with the permission of “write” into the csv file. Then the “DictWriter” method is used, which basically used to write the data of the dictionary into the csv file. In this method, two arguments are passed, first the “csvfile” object and second the “columns” array. Then “writeheader()” method is used to write the header into the csv file. Lastly “writerows” method is used to write the rows to the CSV file, where the “rows” array is passed as an argument.

Execution of Code

Here, the conversion of the Python Dictionary to a CSV file is completed; the code can be executed using the below command:

Code

python dict_to_csv.py
You can also try this code with Online Python Compiler
Run Code


Output

csv output - Text Editor

 

In the above output, there are three columns and five rows, and this CSV file is opened using a text editor. But if you will open the CSV file using Excel, the output will be similar to the below image:

csv output - Excel

Frequently Asked Questions

What are the applications of Python Dictionary?

There are several applications of Python Dictionary, such as Caching, Memoization, Mapping, Transformation, Configuration Management, Associative Arrays, Graph Representation, Lookup Tables, Machine Learning, and Data Science.

Where CSV Files can be opened?

There are different ways of opening a CSV file, such as text editors like visual studio code, vim, sublime Text, Microsoft Excel, and Google Sheets.

How the data can be read from a CSV file using Python?

First, we need to import the CSV module. Then csv file can be opened using the “open()” method with 2 arguments, “file_name” and “r” or “w” permission. Now reader method can be used with the file object as an argument.

How Python Dictionary can be created?

To create a Python Dictionary with the curly braces “{}”. Here is an example for creating key-value pairs: dict = {'name': 'Ninja 1', 'age': 20, 'city': 'Delhi'}.

Conclusion

Python Dictionary can be converted into CSV File using the module called “csv”. The DictWriter() method is basically used to write the data to the csv file. In the article “Python Dictionary to CSV file”, we have discussed Python Dictionary, CSV File, and then the conversion of Python Dictionary to CSV File.

Here are more articles that are recommended to read:

 

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMS, and System Design, etc. as well as some Contests, Test Series, and some Interview Experiences curated by top Industry Experts.

Happy Learning!

Live masterclass