×

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=Nonerestkey=Nonerestval=Nonedialect='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

Problem-solving with algorithm and data structures using Python

What is problem-solving? There is no universal method for solving problems. It's frequently a special process that balances your immediate and long-term goals with your available resources. However, several models emphasise...

3 minutes read.

How to Declare a Variable in Python?

The concept of constants and variables is something that we are studying right from our primary classes. We know that constants are the fixed values whereas variables are those whose...

4 minutes read.

Difference between Sort and Sorted in Python

If you new to Python, it must be confusing the distinction between the Sort and Sorted functions. However, it is important to understand the differences in order to use them...

5 minutes read.

Python program to find Fibonacci series

Python program to find Fibonacci series A Fibonacci series is an integer sequence of 0, 1, 1, 2, 3, 5, 8.... We can identify the Fibonacci series as any number sequence...

2 minutes read.

What Does the Percent Sign (%) Mean in Python?

In python, the percent sign is called modulo operator " %, " which returns the rest of partitioning the left-hand operand by the right-hand operand. Example: value1 = 8 value2 = 2 remainder =...

4 minutes read.

Python divmod() function

Python divmod() function The divmod() function in Python returns a tuple containing the quotient  and the remainder when parameter ‘a’ (divident) is divided by parameter ‘b’ (divisor). Syntax: divmod(a, b) Parameter a: This parameter represents a number you...

1 minute read.

Python Not Equal Operator

Python provides us with many operators to make tasks easier. There are about 7 categories of operators in Python. One of the 7 classifications is the comparison operators. Just as...

3 minutes read.

Python String Lowercase

Python Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Excel Automation with Python

Data analysis is the upcoming technology in the IT sector; this data analysis can be performed easily with the help of data frames or by using excel sheets. The data...

4 minutes read.

Application to get live USD/INR rate Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Python type() Function

Python type() Function The type() function in Python returns the type of an object. The return value is a type object and generally the same object as returned by object.__class__. Syntax class type(object)      ...

1 minute read.

How to Program in Python on Raspberry pi?

Introduction to Python A popular programming tool with simple, complete novice syntax is Python structure of paragraphs, phrases, and words. Due to its widespread use, this has a large community that...

4 minutes read.

Python Multithreading

In python, we can implement multithreading. In this tutorial, we will understand the basics of implementing multithreading in a python programming language. Multithreading is just like multiprocessing. We use it...

4 minutes read.

Python len() function

Python len() function The len() function in Python  returns the number of items in an object. Syntax len(s) Parameter s: This parameter represents a sequence (such as a string, bytes, tuple, list, or range) or...

1 minute read.

iobase Python

All I/O flow classes derive from this conceptual base class. Derived classes will have to execute several of the class's abstract data types. The loop method is supported by all members of...

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 Uses

Python has advanced in recent years to rank among the programming languages that are most often used globally. It is utilized in everything, including machine learning, software testing, and website...

4 minutes read.

Difference between Package and Module in Python

What are Python modules? A file with the “.py” suffix that includes Python or C executable code is known as a module. Multiple Python commands and expressions make compose a module....

3 minutes read.

Python Pascal Triangle

Python Pascal Triangle Pascal triangle A pascal triangle is a number pattern of triangular array of the binomial coefficients. For designing a pascal triangle, we write a function in the program which...

5 minutes read.

Python Goto Statement

We all know that Python is the most basic and widely used programming language in the world. It is also one of the world's most popular and widely used languages....

4 minutes read.