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 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.
Method 1 : Using json.loads() :
# importing the moduleimport json # reading the data from the filewith open('dictionary.txt') as f: data = f.read() print("Data type before reconstruction : ", type(data)) # reconstructing the data as a dictionaryjs = 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() :
# importing the moduleimport ast # reading the data from the filewith open('dictionary.txt') as f: data = f.read() print("Data type before reconstruction : ", type(data)) # reconstructing the data as a dictionaryd = 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
# importing the moduleimport pickle # opening file in write mode (binary)file = open("dictionary.txt", "wb") my_dict = {"Name": "John", "Age": 21, "Id": 28} # serializing dictionary pickle.dump(my_dict, file) # closing the filefile.close() # reading the data from the filewith open('dictionary.txt', 'rb') as handle: data = handle.read() print("Data type before reconstruction : ", type(data)) # reconstructing the data as dictionaryd = 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}



