AppDividend
Latest Code Tutorials

How To Write Python Dictionary To CSV File Example

0

In this tutorial, we will see How To Convert Python Dictionary To CSV File Example. CSV (Comma Separated Values) is the most common file format that is widely supported by many platforms and applications. Use the CSV module from Python’s standard library.

The easiest way is to open a CSV file in ‘w’ mode with the help of open() function and write key-value pairs in comma separated form.

Python Dictionary to CSV

Content Overview

Okay, first, we need to import the CSV module.

import csv

Next, we will define a dictionary.

import csv

dict = {'name': 'krunal', 'age': 26, 'education': 'Engineering'}

Now, we use the open() function to open a file in the writing mode and use the dictionary.keys() method to write the CSV data into the file.

See the following code.

# app.py

import csv

dict = {'name': 'krunal', 'age': 26, 'education': 'Engineering'}

with open('data.csv', 'w') as f:
    for key in dict.keys():
        f.write("%s, %s\n" % (key, dict[key]))

Output

name, krunal
age, 26
education, Engineering

The CSV module contains the DictWriter method that requires the name of the CSV file to write and a list object containing field names.

The writeheader() method writes the first line in CSV file as field names. The subsequent for loop write each row in CSV form to the CSV file.

More Examples

Let’s write more data in the CSV file.

See the following code.

# app.py

import csv

csv_columns = ['Service', 'ShowName', 'Seasons']
dict = [
    {'Service': 'Netflix', 'ShowName': 'Stranger Things', 'Seasons': 3},
    {'Service': 'Disney+', 'ShowName': 'The Mandalorian', 'Seasons': 1},
    {'Service': 'Hulu', 'ShowName': 'Simpsons', 'Seasons': 31},
    {'Service': 'Prime Video', 'ShowName': 'Fleabag', 'Seasons': 2},
    {'Service': 'AppleTV+', 'ShowName': 'The Morning Show', 'Seasons': 1},
]
csv_file = "data.csv"
try:
    with open(csv_file, 'w') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
        writer.writeheader()
        for data in dict:
            writer.writerow(data)
except IOError:
    print("I/O error")

Output

Service,ShowName,Seasons
Netflix,Stranger Things,3
Disney+,The Mandalorian,1
Hulu,Simpsons,31
Prime Video,Fleabag,2
AppleTV+,The Morning Show,1

We are using DictWriter.writerow() to write a single row.

We have used DictWriter.writeheader() if you want a header for your CSV file.

Also, we have used “with statement” for opening files. It’s not only more pythonic and readable but handles the closing for you, even when exceptions occur.

So, in the above example, we have used the following Python CSV functions.

Python CSV.DictWriter()

It creates the object which operates like the regular writer but maps the dictionaries onto output rows.

The fieldnames parameter is the sequence of keys that identify an order in which values in a dictionary passed to the writerow() method are written to file f.

The optional restval parameter specifies the value to be written if a dictionary is missing the key in fieldnames.

If a dictionary passed to the writerow() method contains a key not found in fieldnames, an optional extrasaction parameter indicates what action to take.

If it is set to ‘raise’, the default value, a ValueError is raised.

If it is set to ‘ignore’, extra values in the dictionary are ignored.

Any other optional or keyword arguments are passed to an underlying writer instance.

Python DictWriter.writeheader()

This function is used to write a row with the field names (as specified in the constructor) to the writer’s file object, formatted according to the current dialect. Return the return value of the csvwriter.writerow() call used internally.

Python csvwriter.writerow(row)

The function is used to write the row parameter to the writer’s file object, formatted according to the current dialect. The return value of the call to the write method of the underlying file object.

Python csvwriter.writerows(rows)

This function is used to write all items in rows (an iterable of row objects as described above) to the writer’s file object, formatted according to the current dialect.

Finally, How To Write Python Dictionary To CSV Example is over.

Related Posts

Python CSV Example

How to write a file in Python

Pandas dataframe read_csv Example

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.