• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

The Programming Expert

Solving All of Your Programming Headaches

  • HTML
  • JavaScript
  • jQuery
  • PHP
  • Python
  • SAS
  • Ruby
  • About
You are here: Home / Python / How to Write Python Dictionary to File

How to Write Python Dictionary to File

August 22, 2022 Leave a Comment

To write a dictionary to a file in Python, there are a few ways you can do it depending on how you want the dictionary written.

If you want to write a dictionary just as you’d see it if you printed it to the console, you can convert the dictionary to a string and output it to a text file.

dictionary = {'name': "Bonnie", 'height':65}
  
with open('example.txt', 'w') as f:
     f.write(str(dictionary))

This is the same as if you wanted to store the dictionary as JSON in a text file with the json.dumps().

import json
  
dictionary = {'name': "Bonnie", 'height':65}
  
with open('example.txt', 'w') as f:
     f.write(json.dumps(dictionary))

If you want to write a dictionary as a comma delimited file with the keys and values in separate columns, you can do the following.

import json
  
dictionary = {'name': "Bonnie", 'height':65}
  
with open('example.csv', 'w') as f:
    for k, v in dictionary.items(): 
        f.write(str(k) + "," + str(v))

When working with data in your programs, the ability to easily be able to output to files in a readable way is valuable.

One such case is if you have a dictionary variable and you want to write to a file.

There are a few ways you can write a dictionary to a file depending on how you want the dictionary written.

To write a dictionary just as you’d see it if you printed it to the console, you can convert the dictionary to a string and output it to a text file.

Below shows you how you can simply write a dictionary to a file in Python.

dictionary = {'name': "Bonnie", 'height':65}
  
with open('example.txt', 'w') as f:
     f.write(str(dictionary))

Writing Dictionary to File with json.dumps() in Python

If you want to write a dictionary to a file as JSON, then you can use the json module dumps() function.

dumps() converts dictionaries into JSON strings. If you write a dictionary to a file with json.dumps(), you can then load it with json.loads() at a later time.

Below shows you how to use the json module to write a dictionary to a file in Python.

import json
  
dictionary = {'name': "Bonnie", 'height':65}
  
with open('example.txt', 'w') as f:
     f.write(json.dumps(dictionary))

Writing Dictionary Variable to .csv File in Python

One last way you can write a dictionary variable to a file is if you want to create a comma separated file with keys and values separated by commas.

To do this, you can use the dictionary items() function to get each key/value pair in the dictionary and write on their own line with a comma in between.

Below shows how you can make a csv file from a dictionary in Python.

import json
  
dictionary = {'name': "Bonnie", 'height':65}
  
with open('example.csv', 'w') as f:
    f.write("key,value")
    for k, v in dictionary.items(): 
        f.write(str(k) + "," + str(v))

Hopefully this article has been useful for you to learn how to write dictionary variables to files in Python.

Other Articles You'll Also Like:

  • 1.  Python Negative Infinity – How to Use Negative Infinity in Python
  • 2.  Python max() function – Get Maximum of List or Dictionary with max() Function
  • 3.  Python Destroy Object – How to Delete Objects with del Keyword
  • 4.  Get pandas Series First Element in Python
  • 5.  Generate Random Float Between 0 and 1 Using Python
  • 6.  Check if Number is Larger than N in Python
  • 7.  How to Group By Columns and Find Variance in pandas
  • 8.  math.degrees() Python – How to Convert Radians to Degrees in Python
  • 9.  How to Remove NaN from List in Python
  • 10.  Sorting a List of Tuples by Second Element in Python

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

About The Programming Expert

the programming expert main image

Welcome to The Programming Expert. We are a group of US-based programming professionals who have helped companies build, maintain, and improve everything from simple websites to large-scale projects.

We built The Programming Expert to help you solve your programming problems with useful coding methods and functions in various programming languages.

Search

Learn Coding from Experts on Udemy

Looking to boost your skills and learn how to become a programming expert?

Check out the links below to view Udemy courses for learning to program in the following languages:

Copyright © 2023 · The Programming Expert · About · Privacy Policy