0

I have a text file Phone_book with text as:

{'sunny': ('123456', 'sunny@gmail.com')}. 

I would like to fetch values by calling key(sunny) in python 3. X.

def search_contacts(self):
    key = input('Enter a name to search: ')
    with open('Phone_Book.txt','r') as Phone_book:
        print (Phone_book[key])
    else:
        print('not found')
slavoo
  • 5,798
  • 64
  • 37
  • 39

1 Answers1

0

Use json

import json
dic={'sunny': ('123456', 'sunny@gmail.com')}
json_data = json.dumps(dic) #here json_data contains your dictionary in json format

#To write to a file
file = open('file.json','w')
file.write(json_data)
file.close()

#To read the data
file = open('file.json','r')
json_data = file.read()
file.close()
dic=json.loads(json_data)

##Now use the dic
Prashant Sengar
  • 506
  • 1
  • 7
  • 24
  • Thanks for the reply. It was working well for single line but when I used this module to fetch data from a text file it was not able to fetch the data as a dictionary object. when I used to search for a key I am getting an TypeError as below. Plz help me with that. "Traceback (most recent call last): File "C:/Users/L.sandeep reddy/PycharmProjects/assignments/test2.py", line 13, in print(dict['sunny']) TypeError: string indices must be integers" – sandeep lebaka Jan 19 '19 at 10:36
  • If you have data stored in a text file, it will be read as a string only. You need to save your data as `json` first, and then use it to read the data. I know it is frustrating, but you have to do it like this – Prashant Sengar Jan 23 '19 at 06:06