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

In [3]:
# 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
    
}

 

In [6]:
#import json and pass the dictionary to it
import json
s = json.dumps(book)
s

 

Out[6]:
'{"Bob": {"phone": 252525885, "name": "Bob", "address": "1 green street, NY"}, "Tom": {"phone": 98988988, "name": "Tom", "address": "1 red street, NY"}}'
In [14]:
#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)

 

In [15]:
#lets read back the file
f = open('C://Users//adaba//Documents//Coursera//Projects//writeToTxt.txt', 'r')
read_s = f.read()
read_s

 

Out[15]:
'{"Bob": {"phone": 252525885, "name": "Bob", "address": "1 green street, NY"}, "Tom": {"phone": 98988988, "name": "Tom", "address": "1 red street, NY"}}'
In [16]:
#lets check the type of data of the returned item
type(read_s)

 

Out[16]:
str
In [18]:
# 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)

 

In [19]:
#lets see the result returned by json
book_read_back

 

Out[19]:
{u'Bob': {u'address': u'1 green street, NY',
  u'name': u'Bob',
  u'phone': 252525885},
 u'Tom': {u'address': u'1 red street, NY',
  u'name': u'Tom',
  u'phone': 98988988}}
In [20]:
#what data type is it?
type(book_read_back)

 

Out[20]:
dict
In [21]:
#lets check the records/details for Bob
book_read_back['Bob']

 

Out[21]:
{u'address': u'1 green street, NY', u'name': u'Bob', u'phone': 252525885}
In [22]:
#lets check Bob's phone number
book_read_back['Bob']['phone']

 

Out[22]:
252525885
In [30]:
#lets get all the records from dictionary
for person in book_read_back:
    print(book_read_back[person])

 

{u'phone': 252525885, u'name': u'Bob', u'address': u'1 green street, NY'}
{u'phone': 98988988, u'name': u'Tom', u'address': u'1 red street, NY'}
Hope it helps

 

Similar Posts

Leave a Reply

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