Python Dictionary to CSV

In this Python tutorial, we will discuss the Python dictionary to CSV. Here we will also cover the below examples:

  • Python dictionary to Csv pandas
  • Python dictionary to Csv file
  • Python dictionary to Csv with header
  • Python dictionary to Csv string
  • Python dictionary to Csv format
  • Python dictionary to Csv write
  • Python dictionary to Csv table
  • Python dictionary to Csv columns
  • Python dictionary to Csv append
  • Python write dictionary to Csv row
  • Python json dictionary to Csv

Python Dictionary to CSV

  • In Python to convert a dictionary to CSV use the dictwriter() method. This method is used to insert data into the CSV file. In Python, the CSV module stores the dictwriter() method. It creates an object and works like the dictwriter().
  • To perform this particular task first we will import the CSV module. Next we will initialize a dictionary.

Let’s take an example and check how to convert a dictionary into a CSV file

Source Code:

import csv
  
employee_info = ['emp_id', 'emp_name', 'skills']
  
new_dict = [
{'emp_id': 456, 'emp_name': 'George', 'skills': 'Python'},
{'emp_id': 892, 'emp_name': 'Adam', 'skills': 'Java'},
{'emp_id': 178, 'emp_name': 'Gilchrist', 'skills': 'Mongo db'},
{'emp_id': 155, 'emp_name': 'Elon', 'skills': 'Sql'},
{'emp_id': 299, 'emp_name': 'Mask', 'skills': 'Ruby'},
]
  
with open('test4.csv', 'w') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames = employee_info)
    writer.writeheader()
    writer.writerows(new_dict)

Here we can define the ’employee_info’ as a column name. Now if we want to open a file in the writing mode then we can use the open() function and write the first line in the CSV file we use the writerheader() method. In this example, the writerow() function is to write the row argument to the writer’s file object.

Here is the execution of the following given code

Python dictionary to CSV
Python dictionary to CSV

Another example to check how to convert a dictionary into a CSV

Example:

import csv

my_dictionary = {'values': 678, 'values2': 167, 'values6': 998}

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

In the above code first, we will define a dictionary and use the open() function to open the file, and to write the CSV data into a file we can use the concept of dict.keys().

Here is the Screenshot of the following given code

Python dictionary to CSV method
Python dictionary to CSV method

This is how to convert a dictionary into a CSV file.

Read: Python convert dictionary to an array

Python dictionary to CSV pandas

  • Let us see how to convert the Python dictionary to CSV by using the pandas module.
  • In this example first, we will declare a dictionary and convert it into a dataframe after that we convert it into a CSV file by using the to_csv() function.

Source Code:

import pandas as pd
new_my_dict = [
{'a': 15, 'n': 81, 'p': 177},
{'a': 18, 'n': 24, 'p': 190},
{'a': 19, 'n': 20, 'p': 156},
]
df = pd.DataFrame.from_dict(new_my_dict) 
df.to_csv (r'test8.csv', index = False, header=True)

In the above code first, we need to import the pandas module and then create a dictionary ‘new_my_dict’. Here we are also converting the dictionary to a dataframe. In this example, we can use the method to_csv() within the function we can pass index and header as a parameter but these are optional and we have passed index as ‘false’ and header as ‘True’.

Here is the Screenshot of the following given code

Python dictionary to CSV pandas
Python dictionary to CSV pandas

Read: Get all values from a dictionary Python

Python dictionary to CSV file

  • In Python, a CSV file is a file that contains values break by newline and commas.
  • By using CSV.writer.writerow() we can convert to dictionary into a CSV file. To give a path of a CSV file we can apply the open() file method. In this method, we have passed the ‘w’ keyword as an argument that means to open a stream of a CSV file for writing mode.
  • In Python, to iterate over the key-value pair in the dictionary we can use the combination of for loop and dict.items() method to perform this particular task.

Source Code:

import csv
new_path = open("mytest.csv", "w")
file_dictionary = {"oliva":199,"james":145,"potter":187}

z = csv.writer(new_path)
for new_k, new_v in file_dictionary.items():
    z.writerow([new_k, new_v])

new_path.close()

Note: In the ‘new_path’ variable you have to store your own CSV file.

Here is the implementation of the following given code

Python dictionary to CSV file
Python dictionary to CSV file

Read: Python dictionary of tuples

Python dictionary to CSV with header

  • Here I want to write a specific Python dictionary to CSV with a header.
  • In Python to convert a dictionary to CSV with header use the dictwriter() method. This method is used to insert data into the CSV file. Here we can define ‘header_key’ as a field name.
  • In this example, we will define a dictionary and use the open() function to open the file and the concept of dictwriterheader() method to pass a field name keyword as an argument.

Example:

import csv

new_dictionary = { "Australia" : 456, "Germany" : 2678, "China" : 1890,"Japan":1667}
with open('maintest.csv', 'w', newline='') as csvfile:
    header_key = ['Country', 'Value']
    new_val = csv.DictWriter(csvfile, fieldnames=header_key)

    new_val.writeheader()
    for new_k in new_dictionary:
        new_val.writerow({'Country': new_k, 'Value': new_dictionary[new_k]})

Here is the Output of the following given code

Python dictionary to Csv with header
Python dictionary to Csv with header

Read: Python creates a dictionary from two lists

Python dictionary to CSV string

  • Here we can see how to convert a dictionary into a CSV string.
  • To solve this problem first we need to import an ‘io’ and ‘CSV’ module. Now to export the dictionary data first we open a file that is ‘test8.csv’. The most important point you have to create your own CSV file and put it into the open() function as an argument with the ‘w’ attribute for writing and adjust the newline character equal to a string.
  • Here we create an instance of the dictwriter class and contains an ‘l’ variable. In Python the writerrow() method helps the user to write a list of values and each item contains in a list.

Source Code:

import io
import csv

new_out = io.StringIO()
new_dictionary = [{"emp_name": "OLava", "emp_id": "4567", "skills": "Python"},{"emp_2": "Suzane", "emp_id2": "1678", "skills": "Java"}]
new_path = open("test8.csv", "w")
l = csv.writer(new_path,new_out, quoting=csv.QUOTE_NONNUMERIC)
for m in new_dictionary:
        for new_k, new_val in m.items():
            l.writerow([new_k, new_val])
con_csv = new_out.getvalue()
new_path.close()

Here is the implementation of the following given code

Python dictionary to CSV string
Python dictionary to CSV string
Python dictionary to csv string method
Python dictionary to CSV string method

This is how to convert a dictionary to a CSV string.

Read: Python dictionary pop

Python dictionary to CSV format

Let us see how to convert a Python dictionary to CSV format. To do this task we can apply the open() function and CSV file and ‘w’ keyword as an argument that means to open a stream of a CSV file for writing mode.

Example:

Here we will write the commands to export in CSV format

import csv
my_dict = [{
  "student_id": 1456,
  "stu_nam": "oliva",
  "stu_nam_las": "pollard",
  "age": "26"
}, {
  "student_id": 6789,
  "stu_nam": "john",
  "stu_nam_las": "potter",
  "age": "34"
}, {
  "student_id": 378,
  "stu_nam": "Micheal",
  "stu_nam_las": "brenda",
  "age": "29"
}]

with open("test8.csv", "w", newline="") as csv_file:
  new_val = ["student_id","stu_nam","stu_nam_las","age"] 
  j = csv.DictWriter(csv_file, fieldnames=new_val)
  j.writeheader()
  j.writerows(my_dict)

In the above code first, we will need to import a CSV module then create a list of Python dictionaries. Now declare a list of field names and use the concept of dictwriter. This method is used to write a row of data into the given file.

Output:

Python dictionary to CSV format
Python dictionary to CSV format

Read: Python dictionary contains

Python dictionary to CSV write

  • In Python to access a new CSV file and add the dictionary into it. In this example, we use the CSV writer() method. In Python, the CSVwriter() method helps the user to convert the user data into a string.
  • In this example, the script writes data into the ‘test8.Csv’ file and the writerow() method writes a row of data into the given file and passes ‘new_key’ and ‘new_val’ keywords as an argument.

Source Code:

import csv

my_new_dict = {'Country': 'Egypt', 'Value': '6789'}

with open('test8.csv', 'w') as f:  
    z = csv.writer(f)
    for new_key, new_val in my_new_dict.items():
       z.writerow([new_key, new_val])

Here is the Screenshot of the following given code

Python dictionary to CSV write
Python dictionary to CSV write

Read: Python dictionary comprehension

Python dictionary to CSV columns

  • In this example, we will see how to write a dictionary to CSV columns, and also we will check how to display key elements in the first column and values in the second column.
  • To perform this task we will define a dictionary and use the open() function to open the file and the concept of dictwriter() method to pass a CSV file keyword as an argument.

Source Code:

import csv
new_dictionary = {78:'z', 15:'y', 19:'r'}

with open('maintest.csv', 'w') as f:
    w = csv.writer(f)
    for row in new_dictionary.items():
        w.writerow(row)

Here is the execution of the following given code

When I Open the output in the excel sheet it’s formatted like this

Python dictionary to CSV columns
Python dictionary to CSV columns

Read: Python convert dictionary to list

Python dictionary to CSV append

  • Let us see how to append a row to a CSV file by using the CSV module and dictwriter class.
  • First, we will create a CSV file and insert elements in it. In Python to write and read a CSV file, we can use the CSV() module. To write a CSV file there are two methods that are writer and dictwritter.
  • In this example first, import the writer class and then open your CSV file in append mode. Now if you want to get a writer object then use the concept of CSV.writer() method. After that use writerow() function and within the function pass the list as a parameter.

Source Code:

import csv
from csv import writer

new_row=[9532,'China','Mongodb','26']

with open('maintest.csv', 'a') as f:

    w = writer(f)
    w.writerow(new_row)

	
    f.close()

Here is the Screenshot of the following given code

Python dictionary to CSV append
Python dictionary to CSV append

Read: Python Pandas CSV Tutorial

Python write dictionary to CSV row

  • In Python, the CSV module contains the dictwriter() method that needs CSV files to write on it and store field names. In this example, the writerow() function is to write the row argument to the writer’s file object.

Example:

import csv
  
student_info = ['stu_id', 'stu_name', 'age']
  
new_cs_row = [
{'stu_id': 1890, 'stu_name': 'Liam', 'age': '45'},
{'stu_id': 3456, 'stu_name': 'Noah', 'age': '21'},
{'stu_id': 1678, 'stu_name': 'William', 'age': '27'},
{'stu_id': 9081, 'stu_name': 'Elijah', 'age': '18'},
{'stu_id': 9728, 'stu_name': 'Benjamin', 'age': '17'},
]
  
with open('mytest.csv', 'w') as csvfile:
    i = csv.DictWriter(csvfile, fieldnames = student_info)
    i.writeheader()
    i.writerows(new_cs_row)

Output:

Python write dictionary to CSV row
Python write a dictionary to CSV row

Read: Python NumPy read CSV

Python json dictionary to CSV

  • Here we can see how to convert a JSON dictionary file to a CSV file using Python.
  • In Python, JSON stands for Javascript Object Notation and it is used for data manipulation while CSV file is used formatting for spreadsheets. JSON is a built-in package in Python. To use this module in our code first we have to import the JSON package in Python script. JSON is quite similar to Python dictionary which stores key-value mapping within curly brackets{}.
  • Let us see how to use JSON files in our code and convert them into CSV files.

Source Code:

import json
import csv

with open('newtest.json') as json_file:
	new_info = json.load(json_file)
student_info = new_info['country_name']
new_file_path = open('test9.csv', 'w')
m = csv.writer(new_file_path)
new_num = 0
for stu in student_info:
	if new_num == 0:

		header = stu.keys()
		m.writerow(header)
		new_num += 1

	
	m.writerow(stu.values())
new_file_path.close()

In the above code first thing, we will import the JSON and the CSV module. Now we have to open a JSON file and load the data into a variable and open the CSV file in write mode. After that declare the CSV writer object ‘m’ and ‘new_num’ variable are used for writing headers to CSV file. In this example, the load keyword helps the user to convert JSON data into a dictionary.

Here is the JSON file screenshot

Python json dictionary to CSV
Python JSON dictionary to CSV

Here is the output of the CSV file

Python json dictionary to CSV method
Python JSON dictionary to CSV method

Also, Read: Python find max value in a dictionary

In this Python tutorial, we have discussed the Python dictionary to CSV. Here we have also covered the following examples:

  • Python dictionary to Csv pandas
  • Python dictionary to Csv file
  • Python dictionary to Csv with header
  • Python dictionary to Csv string
  • Python dictionary to Csv format
  • Python dictionary to Csv write
  • Python dictionary to Csv table
  • Python dictionary to Csv columns
  • Python dictionary to Csv append
  • Python write dictionary to Csv row
  • Python json dictionary to Csv