×

Write Dictionary to CSV in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses an interpreter instead of the compiler to run the code. The interpreted language is processed at the run time thus takes less time to run. Python is also interactive, so we can directly run programs in the terminal itself.

Comma Separated Files are very common while working with data in Python. They store data in a tabular form in which values are separated by commas. We can easily transfer data with CSV files to software like Google Sheets, Microsoft Excel. We can easily handle CSV files in Python with the in-built CSV module.

In this port, we are going to discuss how to write a dictionary to CSV using Python.

Writing CSV files

We can easily write and create CSV files using an in-built module called CSV in Python. The CSV.writer() function is used to write the CSV files. We can also CSV.DictWriter() class to write dictionary into a CSV file.

Using csv.Writer()

The CSV module contains the writer function that is used to write in CSV files. We can write anything from a single row, lists to dictionaries. The syntax for the function is:

csv.writer(csvfile, dialect='excel', **fmtparams)

This function returns a writer object which converts the data into a delimited string. Here, argument csvfile is a CSV file that has WRITE permission.  The other parameter is dialect. Dialect is an optional parameter used to set parameters specific to a CSV dialect.

The functions writerow() and wroterows() are used to write rows in a CSV sheet.

Code to Write CSV

import CSV

field_names = ['No', 'Student', 'Class']

students = [

{'No': 1, 'Student': 'Rahul', 'Class': 'Tenth'},

{'No': 2, 'Student': 'Rohan', 'Class': 'Eleventh'},

{'No': 3, 'Student': 'Rishik', 'Class': 'Twelfth'},

{'No': 4, 'Student': 'Ravi', 'Class': 'Tenth'},

{'No': 5, 'Company': 'Rajneesh', 'Class': 'Eleventh'},

]

with open('Example1.csv', 'w') as csvfile:

    writer = csv.writer(csvfile)

    for dicton in students:

        for key, value in dicton.items():

              writer.writerow([key, value])

Output

The following content will be present in a file called Example1.csv after running the CSV:

No1
StudentRahul
ClassTenth
No2
StudentRohan
ClassEleventh
No3
StudentRisk
ClassTwelfth
No4
StudentRavi
ClassTenth
No5
CompanyRajneesh
ClassEleventh
Write Dictionary To CSV In Python

As you can see, this is not the ideal output. We do not want our data in this format most of the time. To get the desired output, we have to use another class instead of CSV.writer().

But first, let us understand the above code.

  • In the first line of code we have imported the module csv.
  • The second line defines the fieldnames which are the column heading for the csv file.
  • After that we have defined our data which we want to write in the csv file. The data is in the dictionary format. The data looks like this:
students = [

{'No': 1, 'Student': 'Rahul', 'Class': 'Tenth'},

{'No': 2, 'Student': 'Rohan', 'Class': 'Eleventh'},

{'No': 3, 'Student': 'Rishik', 'Class': 'Twelfth'},

{'No': 4, 'Student': 'Ravi', 'Class': 'Tenth'},

{'No': 5, 'Company': 'Rajneesh', 'Class': 'Eleventh'},

]
  • In the next line of code, we have opened the Example1.csv file in WRITE mode as the csvfile.
  • Then we have used the csv.writer() function to write the CSV file, which returns a writer object.
  • Then we are first writing the header of the CSV file, which is stored in a list called field_names, and then we are looping through our list of dictionaries one by one and writing the data to the CSV file.

Using csv.DictWriter()

As we discussed earlier, we have to use the CSV.DictWriter() to write the dictionary in a CSV file in the ideal format. The syntax of the DictWriter class is:

class csv.DictReader(file, fieldnames=None, restkey=None, restval=None, dialect='excel', *args, **kwds)   

This returns an object which maps the data in each row of the dictionary to the given key defined by the fieldnames parameter.

The fieldnames are the optional parameter. If not defined, the first row of the file will be the field name for the file.

All other arguments are optional.

Code to Write CSV

import CSV

field_names = ['No', 'Student', 'Class']

students = [

{'No': 1, 'Student': 'Rahul', 'Class': 'Tenth'},

{'No': 2, 'Student': 'Rohan', 'Class': 'Eleventh'},

{'No': 3, 'Student': 'Rishik', 'Class': 'Twelfth'},

{'No': 4, 'Student': 'Ravi', 'Class': 'Tenth'},

{'No': 5, 'Company': 'Rajneesh', 'Class': 'Eleventh'},

]

with open('Names.csv', 'w') as csvfile:

   writer = csv.DictWriter(csvfile, fieldnames = field_names)

   writer.writeheader()

   writer.writerows(students)

Output

Running this code will create a CSV file named Names.csv with the following content:

NoStudentClass
1RahulTenth
2RohanEleventh
3RiskTwelfth
4RaviTenth
5RajneeshEleventh
Write Dictionary To CSV In Python

Let us explain the above code line by line:

  • In the first line of code we have imported the module csv.
  • The second line defines the fieldnames which are the column heading for the csv file.
  • After that we have defined our data which we want to write in the csv file. The data is in the dictionary format. The data looks like this:
students = [

{'No': 1, 'Student': 'Rahul', 'Class': 'Tenth'},

{'No': 2, 'Student': 'Rohan', 'Class': 'Eleventh'},

{'No': 3, 'Student': 'Rishik', 'Class': 'Twelfth'},

{'No': 4, 'Student': 'Ravi', 'Class': 'Tenth'},

{'No': 5, 'Company': 'Rajneesh', 'Class': 'Eleventh'},

]
  • In the next line of code, we have opened the Names.csv file in WRITE mode as the csvfile.
  • Then we have used the DictWriter class to write the CSV file, which returns a writer object.
  • Then we are writing the column header with the function writeheader() and then the actual data with the writerows method.

Related Topics

Loan calculator using Tkinter in Python

Tkinter: Tkinter, part of all common Python distributions, is the de facto method for creating Graphical User Interfaces (GUIs) in Python. The only framework included in the Python standard library is...

4 minutes read.

How to build a Virtual Assistant Using Python

What is a virtual assistant? A virtual assistant is a new and very interesting concept in today’s world. When we hear the word “Virtual Assistant”, we can easily visualize “Jarvis or...

8 minutes read.

Python NewLine

In python, a new line character denoted by "\n" is known as an escape character or escape sequence, and it will force the cursor to change its position to the next...

6 minutes read.

PyPi TensorFlow

It is a free open-source library for high-performative numerical computations. The architecture of TensorFlow allows us for easy deployment and computing across a varied number of platforms and from desktops...

3 minutes read.

Python | Read csv using pandas.read_csv()

Python is an excellent language for performing information analysis, owing to the fantastic biological system of information-driven python packages. Pandas is one of those packages that make taking in and...

4 minutes read.

Python Set clear() Method

Python Set clear() Method The set.clear() method removes all the elements from the set. Syntax set.clear() Parameter NA Return None Example 1 # Python program explaining # the set.clear() method # initializing the set fruits = {"watermelon", "banana", "apple"} # printing the set...

2 minutes read.

Python Kwargs Example

In this article, we'll talk about Python's kwargs notion. In Python, kwargs has two stars and passes a variable number of keyworded argument lists to the function, whereas args has...

5 minutes read.

Python comment symbol

Python programmers frequently use the comment system because, without it, things may quickly become very perplexing. The developers' helpful information is provided in the comments, which helps the reader understand...

3 minutes read.

Append key Value to Dictionary in Python

The Python dictionary is one of the built-in data types. Elements of dictionaries are key-value pairs. In Python, there are numerous ways to add dictionaries. Let's examine some of the...

9 minutes read.

Math Module in Python

In this article, you are going to learn everything in detail about the “ math “ module in Python. We can normally work with general operations using python without importing or...

16 minutes read.

What is online python free IDE

An IDE is an acronym that stands for “Integrated development environment.” It is a software environment that has a software development package that consists of the code editor and builds...

4 minutes read.

Array to String in Python

What is an Array: The idea behind an array is to group several items of the same type, making it easier to locate each element by adding an extra offset to...

4 minutes read.

Python Random Module

The tutorial for the Python random module demonstrates how to produce pseudo-random integers in Python. Random Number Generator (RNG) The RNG (random number generator) generates a series of values with no discernible...

8 minutes read.

Joint Plot in Python

Introduction to Joint plots: The joint plot is the finest approach to evaluate both the specific distribution of each variable and also the connection between the two variables. Three different plots make...

4 minutes read.

Python Dictionary copy() method

Python Dictionary copy() method The dictionary.copy () method in Python returns a copy of the specified dictionary. Syntax dictionary.copy () Parameter NA Return None Example 1 # Python program explaining # the dictionary.copy() method # initialising the dictionary ...

1 minute read.

Python IDE

What is an IDE?  An IDE or an Integrated Development Environment is a type of software where developers can develop many software’s and applications and run the programs inside it. An...

11 minutes read.

Python md5_file() function

Python md5_file() function The md5_file() function in PHP calculates the md5 hash of a given file. Syntax md5_file ( string $filename [, bool $raw_output ] )  Parameter filename(required)- This parameter signifies the file to be calculated. raw_output(optional)- It takes a boolean value that specifies hex or binary...

1 minute read.

Cursor in Python

The cursor is an item that aids in query execution and records retrieval from databases. The cursor is crucial to the execution of the query. In-depth information on the execution...

7 minutes read.

Python Sys Stdout

Python Programming Language: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

Introduction to Scratch programming

Scratch programming is generally designed for children who may create digital stories, games, and animations using the computer language Scratch, which has the largest kid-focused community in the world. Scratch...

3 minutes read.