Python Dict to CSV

Python is a high-level, object-oriented language. Python has a syntax that is similar to English, making it relatively simple to write and read codes. Python runs code using an interpreter rather than a compiler since it is an interpreted language. In addition to lists, which are collections of objects, Python also offers a composite type of data called dictionaries. Dictionaries are Python’s implementation of the associative array, a type of data structure more commonly used in programming. A dictionary is made up of a group of key-value pairs. Every key-value pair links a key to its corresponding value. In this tutorial, we will try to teach you how a Python dictionary can be converted/written into CSV files.

What is a Python Dict?

Python dict is one of the fundamental data structures in Python that makes it easy to write incredibly efficient code. An associative array is the most common name for it. Many other languages refer to this structure as a hash table since the keys of a dict can be hashed. In a Python dict, the keys and values are organized in pairs like “key:value”. They are similar to words and their definitions found in a standard dictionary. Keys in dict are mapped to values. Python dictionaries give us the ability to rapidly obtain a value by associating it with a certain key.

What is a CSV File in Python and Why Use it?

CSV stands for comma-separated values. It is a particular kind of plain/simple text file that organizes tabular data using a particular structure. Because a CSV file is a plain or simple text file, it can only store textual data. Typically, programs that deal with significant amounts of data will produce CSV files. They provide an easy way to import and export data from databases and spreadsheets for use in other programs. We could, for instance, export a dataset’s output to a CSV file, import it into a spreadsheet, and then use it to analyze data, make presentation graphs, or write a published report. Programmatically, CSV files are fairly straightforward to use. CSV files can be worked with directly in any language (like Python) that supports string manipulation and text file input.

How to Convert or Write Python Dict to CSV File?

The most popular file format is CSV (Comma Separated Values), which is supported by a wide range of platforms and programs. The simplest method to open a CSV file in ‘w’ mode using the open() method and writing key-value pairs or dict in comma-separated form is by using the module ‘CSV’ from Python’s standard library. In the examples below, we will demonstrate a few methods to teach you how to write a python dictionary into a CSV file.

Method #1: Converting Python Dictionary to CSV

Example #1: With header

Using the dictwriter() function in Python we can convert/write a dictionary into CSV. Data is inserted into the CSV format file using this approach. The dictwriter() method is included in the CSV module of Python. The CSV module will be imported to do this specific operation first. We will then create a dictionary that will be converted into CSV later on.

Here, the list “data” can be defined as the names of columns. Now, if we wish to open a file in writing mode, we can do so by calling the open() function. We can use the writerheader() function to write the first line of a CSV file. In this code, the writer’s file object is written using the writerow() function.

The output after executing the code:

As can be seen, a CSV file is created in your system.

Example#2: Without a header

Let’s try another example to convert a python dict into a CSV file. In the prior example, we created a list of dict and then converted it into a CSV file. This time, we will create a dict object without specifying the names of columns.

First, we imported the CSV module. We created a python dict and named it ‘my_dict’. To write the data into a CSV file, we have used the concept of dict.keys(). First, we constructed a dictionary and opened the file using the open() function.

Method #2: Python Dictionary to CSV Pandas

Example #1:
We can also use the pandas module to convert a python dict into a CSV file. Let’s look at how to use the pandas module to convert or write the python dict to CSV. Here, we’ll create a dictionary, transform it into a dataframe, and use the to_csv() method to turn that dataframe into a CSV file.

First, in the code above, we imported the pandas module before creating the dictionary “my dict”. The “pd.DataFrame.from dict” function is used to convert the pandas dictionary to a dataframe. The to_csv() method is used to transform the dataframe object into a CSV file. We have passed the value “True” for both index and header even though they are optional.

Method #3: Python Dictionary Conversion to CSV String

Now, we will see how to create a CSV string from a dictionary. First, we must import the “io” and “CSV” modules to do this job. We first open a file, “data.csv”, to export the data of the dictionary. The most crucial step is to make your CSV file, add it as an argument to the open() function, set the ‘w’ attribute for writing, and set the newline character to a string.

Here, we will create a dictwriter class instance that has an ‘x’ variable. The writerrow() method in Python enables the user to create lists of values, each of which is contained in a list.

This will create the following CSV file:

Method #4: Converting the Python Dictionary to CSV Append:

Let’s look at how to add a data row to a CSV using the dictwriter class and CSV module. A CSV file will be created first and elements will be inserted into it. We’ll read and write a CSV file using the CSV module. Using either writer or dictwritter, we can create our CSV file. The writer class will be imported first in this example and then open the file “CSV” in append mode. You can use the CSV.writer() method if you wish to obtain a writer object. Use the writerow() function after that, passing the list as an argument.

You will get the following output when the code is executed in the same directory as your original “test.csv”:

Method #5: Converting the Python Dictionary to CSV Columns

To write a column containing a pair of “key:value” per row from a Python dictionary into a CSV file, follow the steps below.

  • Set the parameter newline=’ ‘ to avoid blank lines when opening the file.csv in writing mode.
  • Create a writer object.
  • Use the dict.items() function to iterate through the dictionary’s (key, value) pairs.
  • By passing a (key, value) tuple to the writer.writerow() method, one (key, value) at a time is written.

This is how the output CSV file will look like:


In this tutorial, we saw the introduction to python dictionary and CSV file. We discussed how you can convert python dict to a csv file. We used different methods and implemented multiple examples to teach you how to convert/write python dict to csv using the pandas module and csv module. You need to be familiar with writing Dict to CSV files if you’re a Python developer.

About the author

Aqsa Yasin

I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.