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:
How to Create a Dictionary in Python
Next article icon

Write a dictionary to a file in Python

Last Updated : 01 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A dictionary store data using key-value pairs. Our task is that we need to save a dictionary to a file so that we can use it later, even after the program is closed. However, a dictionary cannot be directly written to a file. It must first be changed into a format that a file can store and read later. Let’s explore different methods to achieve this.

Using json.dump()

json.dump() function directly writes the dictionary as a JSON object into a file making it easy to read and retrieve later. Since JSON is a text-based format, it can be opened easily and is better for readability purposes.

Python
import json  d = {'Name': "Bob",'Age': 28 }  # writing dictionary to a file as JSON with open('data.json', 'w') as f:     json.dump(d, f) 

Output:

output

data.json file

Explanation: After defining the dictionary, a file named ‘data.json’ is opened in write mode (‘w’), allowing data to be stored in it. Finally, the json.dump(d, f) function is used to directly write the dictionary into the file in JSON format, ensuring that the data is structured and can be easily retrieved later.

Table of Content

  • Using json.dumps()
  • Using pickle.dump()
  • Using str()

Using json.dumps()

json.dumps() function converts a dictionary into a JSON-formatted string, which can then be written to a file manually using write(). This allows adding formatting options like indentation for better readability.

Python
import json  d = {'Name': "Bob", 'Age': 28}  # Convert dictionary to a JSON string and write to file with open('data.json', 'w') as file:     file.write(json.dumps(d, indent=4)) 

Output:

output

data.json file

Explanation: json.dumps(d, indent=4) function is used to convert it into a JSON-formatted string with indentation for better readability. Finally, the write() method is used to store this formatted JSON string in the file, ensuring that the data remains structured and easy to read when accessed later.

Using pickle.dump()

pickle module allows saving a dictionary in binary format, preserving its exact structure. The dump() function serializes the dictionary and writes it to a binary file, which can later be retrieved using load().

Python
from types import resolve_bases import pickle  d = {'Name': "bob", 'Age': 28}  # writing dictionary to a binary file with open('data.pkl', 'wb') as file:     pickle.dump(d, file)  # Reading dictionary from the binary file with open('data.pkl', 'rb') as file:     res = pickle.load(file)  print(res) 

Output:

Output

data.pkl file

{'Name': 'bob', 'Age': 28}

Explanation: pickle.dump(d, file) function serializes the dictionary and writes it to the file, preserving its structure. Later, the same file is opened in binary read mode (‘rb’), and the pickle.load(file) function is used to deserialize the stored data, converting it back into a dictionary.

Using str()

The simplest way to store a dictionary in a file is by converting it into a string using str(), then writing it using write(). This method, however, does not provide a structured format and requires additional processing when reading the data back.

Python
d = {'Name': "Bob", 'Age': 28}  # Convert dictionary to string and write to file with open('data.txt', 'w') as file:     file.write(str(d)) 

Output:

Output

data.txt file

Explanation: str(d) function is used to convert the dictionary into a string format, which is then written to the file using the write() method.



Next Article
How to Create a Dictionary in Python

N

nishanthec19
Improve
Article Tags :
  • Python
  • Python file-handling-programs
  • python-file-handling
Practice Tags :
  • python

Similar Reads

  • Python - Write dictionary of list to CSV
    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,
    4 min read
  • How to save a Python Dictionary to a CSV File?
    CSV (Comma-Separated Values) files are a popular format for storing tabular data in a simple, text-based format. They are widely used for data exchange between applications such as Microsoft Excel, Google Sheets and databases. In this article, we will explore different ways to save a Python dictiona
    4 min read
  • How to Create a Dictionary in Python
    The task of creating a dictionary in Python involves storing key-value pairs in a structured and efficient manner, enabling quick lookups and modifications. A dictionary is an unordered, mutable data structure where each key must be unique and immutable, while values can be of any data type. For exa
    3 min read
  • Add new keys to a dictionary in Python
    In this article, we will explore various methods to add new keys to a dictionary in Python. Let's explore them with examples: Using Assignment Operator (=)The simplest way to add a new key is by using assignment operator (=). [GFGTABS] Python d = {"a": 1, "b": 2} d["c"]
    2 min read
  • How to implement Dictionary with Python3?
    This program uses python's container called dictionary (in dictionary a key is associated with some information). This program will take a word as input and returns the meaning of that word. Python3 should be installed in your system. If it not installed, install it from this link. Always try to ins
    3 min read
  • Dictionary with Tuple as Key in Python
    Dictionaries allow a wide range of key types, including tuples. Tuples, being immutable, are suitable for use as dictionary keys when storing compound data. For example, we may want to map coordinates (x, y) to a specific value or track unique combinations of values. Let's explores multiple ways to
    4 min read
  • Turning a Dictionary into XML in Python
    XML stands for Extensible Markup Language. XML was designed to be self-descriptive and to store and transport data. XML tags are used to identify, store and organize the data. The basic building block of an XML document is defined by tags. An element has a beginning tag and an ending tag. All elemen
    3 min read
  • Ways to create a dictionary of Lists - Python
    A dictionary of lists is a type of dictionary where each value is a list. These dictionaries are commonly used when we need to associate multiple values with a single key. Initialize a Dictionary of ListsThis method involves manually defining a dictionary where each key is explicitly assigned a list
    3 min read
  • How to Add Function in Python Dictionary
    Dictionaries in Python are strong, adaptable data structures that support key-value pair storage. Because of this property, dictionaries are a necessary tool for many kinds of programming jobs. Adding functions as values to dictionaries is an intriguing and sophisticated use case. This article looks
    5 min read
  • How to Alphabetize a Dictionary in Python
    Alphabetizing a dictionary in Python can be useful for various applications, such as data organization and reporting. In this article, we will explore different methods to alphabetize a dictionary by its keys or values. Dictionary OrderingIn Python, dictionaries are a powerful data structure that al
    3 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