Python program to convert Dict of list to CSV


In a dictionary, keys must be unique and immutable, while values can be of any type and can have a list of values. In the case of a dictionary of lists, each key points to a list that can contain multiple elements. 

Here's an example of a dictionary of lists −

data = {'numbers':[1, 2, 3, 4, 5, 6],
'states':['UP', 'Tamil Nadu', 'Telangana', 'Gujarat', 'UP', 'Tamil Nadu'],
'cities':['Agra', 'Chennai', 'Hyderabad', 'Surat', 'Lucknow', 'Coimbatore']})

In the above dictionary, each key is mapped to a list of values. For instance, the 'states' key maps to the list ['UP', 'Tamil Nadu', 'Telangana', 'Gujarat', 'UP', 'Tamil Nadu'].

On the other hand, A CSV (Comma-Separated Values) file is a plain text file that stores tabular data in a simple, comma-separated format. Each line in the file typically represents a row of data, and the values within each row are separated by commas. The first line often serves as the header row, containing the column names.

Here's an example of a CSV file representing the data from the dictionary of lists mentioned earlier −

numbers,states,cities
1,UP,Agra
2,Tamil Nadu,Chennai
3,Telangana,Hyderabad
4,Gujarat,Surat
5,UP,Lucknow
6,Tamil Nadu,Coimbatore

When converting a dictionary of lists to a CSV file, the general approach involves iterating over the dictionary keys and values to write them into the CSV file. There are a few different approaches we are going to discuss in this article.

Using the csv module

The csv module in Python provides several methods for writing data to a CSV file. These methods are part of the csv.writer class and allow us to write individual rows or multiple rows of data to the CSV file.

  • writerow(row) − This method writes a single row of data to the CSV file.

  • writerows(rows) − This method writes multiple rows of data to the CSV file.

Additionally, we can use the zip() function to iterate over the values of the dictionary of lists row by row.

The zip() function takes multiple iterables (in this case, the lists of values) and returns an iterator that aggregates elements from each iterable. Which can effectively transpose the data from a column-based representation to a row-based representation.

Example

Here is an example, to convert the dictionary of lists to a CSV file using the Python csv module and its methods.

import csv

# define the function
def dict_to_csv(dictionary, filename):
    keys = list(dictionary.keys())
    values = list(dictionary.values())

    with open(filename, 'w', newline='') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(keys)
        writer.writerows(zip(*values))

# create a dictionary of lits
data = {'numbers':[1, 2, 3, 4, 5, 6],
        'colors':['red','green', 'yellow', 'blue', 'brown'],
        'fruits':['apples','Avocados', 'Pineapples', 'Blueberries', 'Dates']}

print('Input Dictionary of lits:', data)
print()

# Convert dictionary to CSV
dict_to_csv(data, 'Output\output2.csv')
print('Output:')
print('The converted CSV file is created successfully in our working directory.')

Output

Input Dictionary of lits: {'numbers': [1, 2, 3, 4, 5, 6], 'colors': ['red', 'green', 'yellow', 'blue', 'brown'], 'fruits': ['apples', 'Avocados', 'Pineapples', 'Blueberries', 'Dates']}

Output:
The converted CSV file is created successfully in our working directory.

The following image shows the converted csv file created in the working directory.

Using the pandas library

The pandas library provides many additional functionalities for handling and manipulating data, such as data filtering, aggregation, sorting, and more. It supports writing CSV files from a DataFrame using the to_csv() function.

Example

In this approach, we initially create a pandas DataFrame from the dictionary of lists, and then we will use the to_csv() method to create a CSV file from the Dataframe.

Let’s see an example using the pandas library to convert the dictionary of list to a CSV file.

import pandas as pd

def dict_to_csv(dictionary, filename):
    df = pd.DataFrame(dictionary)
    df.to_csv(filename, index=False)

# create a dictionary of lits
data = {'nums':[1, 2, 3, 4, 5, 6],
   'states':['UP','Tamil Nadu', 'Telangana', 'Gujarat', 'UP', 'Tamil Nadu'],
   'cities':['Agra','Chennai', 'Hyderabad', 'Surat', 'Lucknow', 'Coimbatore']}

print('Input Dictionary of lits:', data)
print()

# Convert dictionary to CSV
dict_to_csv(data, 'Output\output.csv')
print('Output:')
print('The converted CSV file is created successfully in our working directory.')

Output

Input Dictionary of lits: {'nums': [1, 2, 3, 4, 5, 6], 'states': ['UP', 'Tamil Nadu', 'Telangana', 'Gujarat', 'UP', 'Tamil Nadu'], 'cities': ['Agra', 'Chennai', 'Hyderabad', 'Surat', 'Lucknow', 'Coimbatore']}

Output:
The converted CSV file is created successfully in our working directory.

The following image shows the converted csv file created in the working directory.

The above two examples demonstrate the different approaches to converting a dictionary of lists to a CSV file using Python programming.

Updated on: 29-Aug-2023

342 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements