Dictionary to file in Python

What is Dictionary:

A dictionary in  Python is a data structure used to store values in key: value pairs. This makes it different from other data structures of Python like lists, tuples, and sets. In a dictionary, each key has its associate value.

Syntax of Dictionary:

The dictionaries in Python are created in curly bracket {}, and elements are separated by commas. The dictionary holds a pair of keys and values. The dictionary can also be created by dict().dict() is a built-in pre-defined function available in Python.

To store the dictionary in file

import json as js

# Sample dictionary
dict1 = {"Roll no":1234,"name":"akshay","department":"Testing"}

# file path
file1 = "dict1.js"

# Write dictionary to file
with open(file1, "w") as ak:
    js.dump(dict1, ak)

#Read the contents of the file
with open(file1, "r") as ak:
  jump = ak.read()

print(jump)

 

in Python we have to import the JSON library of Python.JavaScript Object Notation(JSON) is used to transfer data as text.

After this, we have to store this JSON file. We created the one dictionary and stored this dictionary in a JSON file. To read and  write in files in Python we have to methods write and read respectivly. To write or read the file we have to first open the file and then we can do operations on that file.

Leave a Comment

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

Scroll to Top