This is a quick to create a dictionary object , write it to a JSON file and then read back the file and convert it to a dictionary and access the items in the dictionary.
Credit to : codebasics. You can check him out on Youtube
# lets create a dictionary of books
book = {}
book['Tom'] = {
'name':'Tom',
'address':'1 red street, NY',
'phone':98988988
}
book['Bob'] = {
'name':'Bob',
'address':'1 green street, NY',
'phone':252525885
}
#import json and pass the dictionary to it
import json
s = json.dumps(book)
s
#lets write the string returned by json to a txt file
with open('C://Users//adaba//Documents//Coursera//Projects//writeToTxt.txt', 'w') as f:
f.write(s)
#lets read back the file
f = open('C://Users//adaba//Documents//Coursera//Projects//writeToTxt.txt', 'r')
read_s = f.read()
read_s
#lets check the type of data of the returned item
type(read_s)
# it is a json string object. we want to get it back into a dictionary format so we can work with it easily
book_read_back = json.loads(read_s)
#lets see the result returned by json
book_read_back
#what data type is it?
type(book_read_back)
#lets check the records/details for Bob
book_read_back['Bob']
#lets check Bob's phone number
book_read_back['Bob']['phone']
#lets get all the records from dictionary
for person in book_read_back:
print(book_read_back[person])