The Wayback Machine - https://web.archive.org/web/20240728003013/https://www.geeksforgeeks.org/write-a-dictionary-to-a-file-in-python/
Open In App

Write a dictionary to a file in Python

Last Updated : 29 Dec, 2020
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Dictionary is used to store data values in the form of key:value pairs. In this article we will see how to write dictionary into a file. Actually we can only write a string to a file. If we want to write a dictionary object, we either need to convert it into string using json or serialize it.

Method:1 Storing Dictionary With Object Using Json

Approach:

  • Import Json
  • Create A Dictionary  in-order pass it into text file.
  • Open file in write mode.
  • Use json.dumps() for json string

Code:

Python3




import json
  
details = {'Name': "Bob",
          'Age' :28}
  
with open('convert.txt', 'w') as convert_file:
     convert_file.write(json.dumps(details))


Output:

Method 2: Using Loop

Approach:

  • Create a dictionary.
  • Open a file in write mode.
  • Here We Use For Loop With Key Value Pair Where “Name”  is Key And  “Alice” is Value So For loop Goes Through Each Key:Value Pair For Each Pairs 
  • Then f.write() Function Just Write’s The Output In Form Of String “%s” 

Code:

Python3




details={'Name' : "Alice",
         'Age' : 21,
         'Degree' : "Bachelor Cse",
         'University' : "Northeastern Univ"}
  
with open("myfile.txt", 'w') as f: 
    for key, value in details.items(): 
        f.write('%s:%s\n' % (key, value))


Output:

Method:3 Without Using loads(),dumps().

Here The Steps Are Followed Above Methods But in Write We Use Str() Method Which Will Convert The Given Dictionary Into String

Python3




details = {'Name': "Bob", 'Age' :28} 
  
with open('file.txt','w') as data: 
      data.write(str(details))


Output:



Similar Reads

Read content from one file and write it into another file
Prerequisite: Reading and Writing to text files in Python Python provides inbuilt functions for creating, writing, and reading files. Two types of files can be handled in python, normal text files and binary files (written in binary language,0s, and 1s). Text files: In this type of file, Each line of text is terminated with a special character call
2 min read
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, dialect='excel') Parameters: csvfile: A file object
4 min read
Python | Pretty Print a dictionary with dictionary value
This article provides a quick way to pretty How to Print Dictionary in Python that has a dictionary as values. This is required many times nowadays with the advent of NoSQL databases. Let's code a way to perform this particular task in Python. Example Input:{'gfg': {'remark': 'good', 'rate': 5}, 'cs': {'rate': 3}} Output: gfg: remark: good rate: 5
7 min read
Python - Write Bytes to File
Files are used in order to store data permanently. File handling is performing various operations (read, write, delete, update, etc.) on these files. In Python, file handling process takes place in the following steps: Open filePerform operationClose file There are four basic modes in which a file can be opened― read, write, append, and exclusive c
2 min read
Python | Write multiple files data to master file
Given a number of input files in a source directory, write a Python program to read data from all the files and write it to a single master file. Source directory contains n number of files, and structure is same for all files. The objective of this code is to read all the files one by one and then append the output into a single master file having
2 min read
Python | Create and write on excel file using xlsxwriter module
XlsxWriter is a Python module for writing files in the XLSX file format. It can be used to write text, numbers, and formulas to multiple worksheets. Also, it supports features such as formatting, images, charts, page setup, auto filters, conditional formatting and many others.Use this command to install xlsxwriter module: pip install xlsxwriter Not
3 min read
How to write the output to HTML file with Python BeautifulSoup?
In this article, we are going to write the output to an HTML file with Python BeautifulSoup. BeautifulSoup is a python library majorly used for web scraping but in this article, we will discuss how to write the output to an HTML file. Modules needed and installation: pip install bs4 Approach: We will first import all the required libraries.Make a g
2 min read
How to write to an HTML file in Python ?
Python language has great uses today in almost every field, it can be used along with other technologies to make our lives easier. One such use of python is getting the data output in an HTML file. We can save any amount of our input data into an HTML file in python using the following examples in two ways. Example 1: Creating an HTML file and savi
2 min read
How to save a Python Dictionary to a CSV File?
Prerequisites: Working with csv files in Python CSV (comma-separated values) files are one of the easiest ways to transfer data in form of string especially to any spreadsheet program like Microsoft Excel or Google spreadsheet. In this article, we will see how to save a PYthon dictionary to a CSV file. Follow the below steps for the same. Import cs
2 min read
How to read Dictionary from File in Python?
A Dictionary in Python is collection of key-value pairs, where key is always unique and oftenly we need to store a dictionary and read it back again. We can read a dictionary from a file in 3 ways: Using the json.loads() method : Converts the string of valid dictionary into json form. Using the ast.literal_eval() method : Function safer than the ev
2 min read
three90RightbarBannerImg