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 module import json # reading the data from the file with open ( 'dictionary.txt' ) as f: data = f.read() print ( "Data type before reconstruction : " , type (data)) # reconstructing the data as a dictionary 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()
:
# importing the module import ast # reading the data from the file with open ( 'dictionary.txt' ) as f: data = f.read() print ( "Data type before reconstruction : " , type (data)) # reconstructing the data as a dictionary 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
# importing the module import 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 file file .close() # reading the data from the file with open ( 'dictionary.txt' , 'rb' ) as handle: data = handle.read() print ( "Data type before reconstruction : " , type (data)) # reconstructing the data as dictionary 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}