How to read Dictionary from File in Python?
Last Updated :
12 Nov, 2021
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 eval function and can be used for interconversion of all data types other than dictionary as well.
- Using the
pickle.loads() method : We can also use Pickle module if the file is serialized into a character stream.
Input File:

Method 1 : Using json.loads() :
import json
with open('dictionary.txt') as f:
data = f.read()
print("Data type before reconstruction : ", type(data))
js = json.loads(data)
print("Data type after reconstruction : ", type(js))
print(js)
|
Output :
Data type before reconstruction : <class 'str'>
Data type after reconstruction : <class 'dict'>
{'Name': 'John', 'Age': 21, 'Id': 28}
Method 2 : Using ast.literal_eval() :
import ast
with open('dictionary.txt') as f:
data = f.read()
print("Data type before reconstruction : ", type(data))
d = ast.literal_eval(data)
print("Data type after reconstruction : ", type(d))
print(d)
|
Output :
Data type before reconstruction : <class 'str'>
Data type after reconstruction : <class 'dict'>
{'Name': 'John', 'Age': 21, 'Id': 28}
Method 3 : We can use the Pickle module for the same purpose, but this method will only work if the file is serialized into a character stream and not in text format. To know more about Pickling in Python click here
import pickle
file = open("dictionary.txt", "wb")
my_dict = {"Name": "John",
"Age": 21,
"Id": 28}
pickle.dump(my_dict, file)
file.close()
with open('dictionary.txt', 'rb') as handle:
data = handle.read()
print("Data type before reconstruction : ", type(data))
d = pickle.loads(data)
print("Data type after reconstruction : ", type(d))
print(d)
|
Output :
Data type before reconstruction : <class 'bytes'>
Data type after reconstruction : <class 'dict'>
{'Name': 'John', 'Age': 21, 'Id': 28}
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...