Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Convert Dictionary to List of Tuples - Python
Next article icon

Convert Dict of List to CSV - Python

Last Updated : 29 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

To convert a dictionary of lists to a CSV file in Python, we need to transform the dictionary's structure into a tabular format that is suitable for CSV output. A dictionary of lists typically consists of keys that represent column names and corresponding lists that represent column data.
For example, given a dictionary with keys key1, key2, and key3 and values like ['a', 'b', 'c'], ['d', 'e', 'f'] and ['g', 'h', 'i'], the resulting CSV will have key1, key2, and key3 as headers and the lists as rows under these headers, making the data easy to process in a tabular format.

Using pandas

Pandas is especially useful when dealing with large datasets due to its optimized handling of data structures and efficient writing to CSV. It can automatically handle various data types, offering simplicity and speed for converting a dictionary of lists into a CSV format.

Python
import pandas as pd  d = {     "key1": ['a', 'b', 'c'],      "key2": ['d', 'e', 'f'],      "key3": ['g', 'h', 'i'] }  # Convert dictionary to DataFrame df = pd.DataFrame(d)  # Save to CSV df.to_csv("test.csv", index=False) 

Output

output
test.csv

Explanation:

  • pd.DataFrame(d) converts the dictionary into a DataFrame.
  • df.to_csv("test.csv", index=False) saves the DataFrame as a CSV file without including row indices.

Table of Content

  • Using csv.Dictwriter
  • Using csv.writer
  • Using json

Using csv.Dictwriter

csv.DictWriter class from Python’s built-in csv module provides a direct way to handle dictionaries and allows us to write data to CSV in a structured manner. This method is efficient for moderately sized datasets and works well when we want to interact with dictionaries directly without needing an external library like Pandas.

Python
import csv  d = {     "key1": ['a', 'b', 'c'],      "key2": ['d', 'e', 'f'],      "key3": ['g', 'h', 'i'] }  # Writing to CSV using DictWriter with open("test.csv", "w", newline='') as outfile:     fieldnames = d.keys()     writerfile = csv.DictWriter(outfile, fieldnames=fieldnames)          writerfile.writeheader()          rows = [dict(zip(fieldnames, row)) for row in zip(*d.values())]     writerfile.writerows(rows) 

Output:

output
test.csv

Explanation:

  • open("test.csv", "w", newline='') as outfile opens test.csv for writing.
  • csv.DictWriter(outfile, fieldnames=d.keys()) prepares to write dictionaries to CSV.
  • writerfile.writeheader() writes column headers.
  • writerfile.writerows(rows) converts lists to rows and writes them to CSV.

Using csv.writer

This approach uses Python's built-in csv.writer class in combination with the zip function. zip () transposes the dictionary values into rows, making it easy to write them to a CSV file. It is a straightforward method for smaller datasets and doesn’t require any additional libraries or complex operations.

Python
import csv  # Dictionary of lists d = {     "key1": ['a', 'b', 'c'],      "key2": ['d', 'e', 'f'],      "key3": ['g', 'h', 'i'] }  # Writing to CSV using csv.writer with open("test.csv", "w", newline='') as outfile:     writerfile = csv.writer(outfile)     writerfile.writerow(d.keys())     writerfile.writerows(zip(*d.values())) 

Output:

output
test.csv

Explanation:

  • open("test.csv", "w", newline='') as outfile opens test.csv for writing.
  • csv.writer(outfile) prepares to write to the CSV file.
  • writerfile.writerow(d.keys()) writes the dictionary keys as the header row.
  • writerfile.writerows(zip(*d.values())) transposes the dictionary values to write them as rows. Each list corresponds to a column.

Using json

This method involves first converting the dictionary to a JSON format and then exporting it to a CSV. While not the most efficient for large datasets, it is flexible and can be useful when we want to perform additional operations on the data in JSON format before converting it to CSV.

Python
import json import csv  d = {     "key1": ['a', 'b', 'c'],      "key2": ['d', 'e', 'f'],      "key3": ['g', 'h', 'i'] }  # Convert dictionary to JSON string json_data = json.dumps(d)  # Write to CSV with open("test.csv", "w", newline='') as outfile:     writerfile = csv.writer(outfile)     writerfile.writerow(d.keys())     writerfile.writerows(zip(*d.values())) 

Output:

output
test.csv

Explanation:

  • with open("test.csv", "w", newline='') as outfile opens test.csv for writing.
  • csv.writer(outfile) prepares to write data into the CSV file.
  • writerfile.writerow(d.keys()) writes the dictionary keys (column names) as the header row.
  • writerfile.writerows(zip(*d.values())) transposes the dictionary values to rows and writes them to the CSV file.

Next Article
Convert Dictionary to List of Tuples - Python

S

sainimansi
Improve
Article Tags :
  • Python
  • Python Programs
  • python-dict
  • Python dictionary-programs
Practice Tags :
  • python
  • python-dict

Similar Reads

  • Python Convert Dict of Lists to Dict of Sets
    In Python, converting a dictionary of lists to a dictionary of sets is a valuable process for optimizing data structures. This transformation enhances efficiency by eliminating duplicates and enabling efficient membership testing. Utilizing built-in functions like set() and list comprehension simpli
    3 min read
  • Python - Convert List to List of dictionaries
    We are given a lists with key and value pair we need to convert the lists to List of dictionaries. For example we are given two list a=["name", "age", "city"] and b=[["Geeks", 25, "New York"], ["Geeks", 30, "Los Angeles"], ["Geeks", 22, "Chicago"]] we need to convert these keys and values list into
    4 min read
  • Convert List of Lists to Dictionary - Python
    We are given list of lists we need to convert it to python . For example we are given a list of lists a = [["a", 1], ["b", 2], ["c", 3]] we need to convert the list in dictionary so that the output becomes {'a': 1, 'b': 2, 'c': 3}. Using Dictionary ComprehensionUsing dictionary comprehension, we ite
    3 min read
  • Python Convert Dictionary to List of Values
    Python has different types of built-in data structures to manage your data. A list is a collection of ordered items, whereas a dictionary is a key-value pair data. Both of them are unique in their own way. In this article, the dictionary is converted into a list of values in Python using various con
    3 min read
  • Convert Dictionary to List of Tuples - Python
    Converting a dictionary into a list of tuples involves transforming each key-value pair into a tuple, where the key is the first element and the corresponding value is the second. For example, given a dictionary d = {'a': 1, 'b': 2, 'c': 3}, the expected output after conversion is [('a', 1), ('b', 2
    3 min read
  • Convert a List to Dictionary Python
    We are given a list we need to convert the list in dictionary. For example, we are given a list a=[10,20,30] we need to convert the list in dictionary so that the output should be a dictionary like {0: 10, 1: 20, 2: 30}. We can use methods like enumerate, zip to convert a list to dictionary in pytho
    2 min read
  • Python | Convert list of tuples into list
    In Python we often need to convert a list of tuples into a flat list, especially when we work with datasets or nested structures. In this article, we will explore various methods to Convert a list of tuples into a list. Using itertools.chain() itertools.chain() is the most efficient way to flatten a
    3 min read
  • Python | Convert list of tuples into digits
    Given a list of tuples, the task is to convert it into list of all digits which exists in elements of list. Let’s discuss certain ways in which this task is performed. Method #1: Using re The most concise and readable way to convert list of tuple into list of all digits which exists in elements of l
    6 min read
  • Python | Convert list of tuples to list of list
    Converting list of tuples to list of lists in Python is a task where each tuple is transformed into list while preserving its elements. This operation is commonly used when we need to modify or work with the data in list format instead of tuples. Using numpyNumPy makes it easy to convert a list of t
    3 min read
  • Python | Dictionary to list of tuple conversion
    Inter conversion between the datatypes is a problem that has many use cases and is usual subproblem in the bigger problem to solve. The conversion of tuple to dictionary has been discussed before. This article discusses a converse case in which one converts the dictionary to list of tuples as the wa
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences