Open In App

Python – Write dictionary of list to CSV

Last Updated : 12 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss the practical implementation of how to write a dictionary of lists to CSV.

We can use the csv module for this. The csvwriter file object supports three methods such as csvwriter.writerow(), csvwriter.writerows(), csvwriter.writeheader(). 

Syntax:

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

Parameters:

  • csvfile: A file object with write() method.
  • dialect (optional): Name of the dialect to be used.

Method 1 : Using csv.writerow() 

To write a dictionary of list to CSV files, the necessary functions are csv.writer(), csv.writerow(). This method writes a single row at a time. Field rows can be written using this method.

Syntax :

csvwriter.writerow(row)

Example 1:

Python3




# import the csv package
import csv
 
# create a csv file with desired name
#and store it in a variable
with open('test.csv', 'w') as testfile:
   
    # store the desired header row as a list
    # and store it in a variable
    fieldnames = ['first_field', 'second_field', 'third_field']
     
    # pass the created csv file and the header
    # rows to the Dictwriter function
    writer = csv.DictWriter(testfile, fieldnames=fieldnames)
     
    # Now call the writeheader function,
    # this will write the specified rows as
    # headers of the csv file
    writer.writeheader()


Output:

Alternatively, a dictionary of lists can be converted to a CSV file using only the csv.writerow() function,  just by iterating through each key-value pair in the dictionary as shown

Example 2:

Python3




# create a dictionary of list
test = {'Age': [52, 24, 31, 47, 51, 61],
        'Sex': ['F', 'M', 'M', 'F', 'F', 'M'],
        'height': [143, 163, 144, 154, 174, 177],
        'weight': [77, 66, 59, 53, 71, 63], }
 
# create a csv file called test.csv and
# store it a temp variable as outfile
with open("test.csv", "w") as outfile:
   
   # pass the csv file to csv.writer.
    writer = csv.writer(outfile)
     
    # convert the dictionary keys to a list
    key_list = list(test.keys())
     
    # find the length of the key_list
    limit = len(key_list)
     
    # the length of the keys corresponds to
    # no. of. columns.
    writer.writerow(test.keys())
     
    # iterate each column and assign the
    # corresponding values to the column
    for i in range(limit):
        writer.writerow([test[x][i] for x in key_list])


Output:

Method 2 : Using csv.writerows() 

To write a dictionary of list to CSV files, the necessary functions are csv.writer(), csv.writerows(). This method writes all elements in rows (an iterable of row objects as described above) to the writer’s file object.

Syntax

csvwriter.writerows(rows)

Example 1:

Python3




# import the csv package
import csv
 
# create a file called test.csv
# and store it in a temporary variable
with open('test.csv', 'w') as testfile:
   
    # pass the temp variable to csv.writer
    # function
    csvwriter = csv.writer(testfile)
     
    # pass the row values to be stored in
    # different rows
    csvwriter.writerows([['row1'], ['row2'], ['row3'],
                         ['row4'], ['row5'], ['row6']])


Output:

Example 2:

 Here we are going to create a csv file  test.csv and store it in a variable as outfile.

Python3




# create a dictionary of list
test = {'Age': [52, 24, 31, 47, 51, 61],
        'Sex': ['F', 'M', 'M', 'F', 'F', 'M'],
        'height': [143, 163, 144, 154, 174, 177],
        'weight': [77, 66, 59, 53, 71, 63], }
 
# create a csv file  test.csv and store
# it in a variable as outfile
with open("test.csv", "w") as outfile:
 
    # pass the csv file to csv.writer function.
    writer = csv.writer(outfile)
 
    # pass the dictionary keys to writerow
    # function to frame the columns of the csv file
    writer.writerow(test.keys())
   
    # make use of writerows function to append
    # the remaining values to the corresponding
    # columns using zip function.
    writer.writerows(zip(*test.values()))


Output:

Method 3 : Using csv.writeheader() 

This method writes a row with the field names specified, as header to the csv.dictwriter object.

Syntax

csvwriter.writeheader()

Example:

Python3




# import the csv package
import csv
 
# create a csv file with desired name
#and store it in a variable
with open('test.csv', 'w') as testfile:
   
    # store the desired header row as a list
    # and store it in a variable
    fieldnames = ['first_field', 'second_field', 'third_field']
     
    # pass the created csv file and the header
    # rows to the Dictwriter function
    writer = csv.DictWriter(testfile, fieldnames=fieldnames)
     
    # Now call the writeheader function,
    # this will write the specified rows as
    # headers of the csv file
    writer.writeheader()


Output:



Previous Article
Next Article

Similar Reads

Python program to read CSV without CSV module
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the nam
3 min read
How to create multiple CSV files from existing CSV file using Pandas ?
In this article, we will learn how to create multiple CSV files from existing CSV file using Pandas. When we enter our code into production, we will need to deal with editing our data files. Due to the large size of the data file, we will encounter more problems, so we divided this file into some small files based on some criteria like splitting in
3 min read
Load CSV data into List and Dictionary using Python
Prerequisites: Working with csv files in Python CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the com
2 min read
Convert Dictionary Value list to Dictionary List Python
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to convert dictionary list to nested records dictionary taking each index of dictionary list value and flattening it. This kind of problem can have application in many domains. Let's discuss certain ways in which this task can be performed. Input : test_list =
9 min read
How to save a Python Dictionary to a CSV File?
Prerequisites: Working with csv files in Python CSV (comma-separated values) files are one of the easiest ways to transfer data in form of string especially to any spreadsheet program like Microsoft Excel or Google spreadsheet. In this article, we will see how to save a PYthon dictionary to a CSV file. Follow the below steps for the same. Import cs
2 min read
Python program to update a dictionary with the values from a dictionary list
Given a dictionary and dictionary list, update the dictionary with dictionary list values. Input : test_dict = {"Gfg" : 2, "is" : 1, "Best" : 3}, dict_list = [{'for' : 3, 'all' : 7}, {'and' : 1, 'CS' : 9}] Output : {'Gfg': 2, 'is': 1, 'Best': 3, 'for': 3, 'all': 7, 'and': 1, 'CS': 9} Explanation : All dictionary keys updated in single dictionary. I
8 min read
Python Program to create a sub-dictionary containing all keys from dictionary list
Given the dictionary list, our task is to create a new dictionary list that contains all the keys, if not, then assign None to the key and persist of each dictionary. Example: Input : test_list = [{'gfg' : 3, 'is' : 7}, {'gfg' : 3, 'is' : 1, 'best' : 5}, {'gfg' : 8}]Output : [{'is': 7, 'best': None, 'gfg': 3}, {'is': 1, 'best': 5, 'gfg': 3}, {'is':
8 min read
Write a dictionary to a file in Python
Dictionary is used to store data values in the form of key:value pairs. In this article we will see how to write dictionary into a file. Actually we can only write a string to a file. If we want to write a dictionary object, we either need to convert it into string using json or serialize it. Method:1 Storing Dictionary With Object Using Json Appro
2 min read
Python | Convert flattened dictionary into nested dictionary
Given a flattened dictionary, the task is to convert that dictionary into a nested dictionary where keys are needed to be split at '_' considering where nested dictionary will be started. Method #1: Using Naive Approach Step-by-step approach : Define a function named insert that takes two parameters, a dictionary (dct) and a list (lst). This functi
8 min read
Python | Convert nested dictionary into flattened dictionary
Given a nested dictionary, the task is to convert this dictionary into a flattened dictionary where the key is separated by '_' in case of the nested key to be started. Method #1: Using Naive Approach Step-by-step approach : The function checks if the input dd is a dictionary. If it is, then it iterates over each key-value pair in the dictionary, a
8 min read
Article Tags :
Practice Tags :