Python Forum

Full Version: [for a h/w project] How to save and get back dictionary in a .json file in TinyDB.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hi
I am trying to save a dictionary named Dict on a .json file using TinyDB. The rest of the program is working except the part wherein the Dict is saved into the json file and then retrieved when the program is relaunched.

I tried to do something but got a TypeError instead.
this is the STARTING end of the program
from tinydb import TinyDB,Query
DB=TinyDB('DB.json')
password='adis1999'

#------Authenticator function---------
def authenticator():
    input_pwd=input('Enter Password:')
    if input_pwd==password:
        print('Access Granted!\n')
        global Dict
        Dict=DB['_default']
        menu()
    else:
        print('Wrong Password!\n')
        authenticator()
and this is the ENDING end of the program:
print('Program Terminated!')
DB['_default']=Dict
and finally this is the ERROR message:
TypeError: 'TinyDB' object is not subscriptable

I would be attaching the .py file also if anybody is interested.
pls forgive me for bad quality of code. i'm just a student Big Grin
the code is in the file PHONEBOOK-1.py
https://drive.google.com/drive/folders/1...sp=sharing

pls reply to me if u need more information
TinyDB has a nice documentation page that explains how to store and retrieve data from the database. You could perhaps start by reading this page and writing similar code. The 'Basic Usage' section seems particularly attractive.
Hi
For my project, I wanted to make a phonebook that saves data permanently. so I chose TinyDB because everyone else is telling me that its perfect for small projects.

Currently I am having trouble saving my dictionary named Dict into the database and then retrieving it when the program is run again.

Why like this? Overview:
The program runs fully on that one dictionary. I know that there are other tutorials showing how to save data into the DB and directly retrieve them and process them using Query(). But I have coded in such a way that everything works with only one dictionary. Now I just need to be able to save the data permanently in the computer and then retrieve it when run again.

A] this is how I Initialized the database:
from tinydb import TinyDB,Query
DB=TinyDB('DB.json')
Document=class Document #getting syntaxError here. does this need to be
#imported as module like math module?
if DB.contains(doc_id=1)==True:   #initializing Dict
    Dict=DB.get(doc_id=1)
else:
    Dict={}
I didn't import json. Is that needed?

B] this is how I tried to retrieve the Dictionary named Dict
from the authenticator() function that I have created.
def authenticator():
    input_pwd=input('Enter Password:')
    if input_pwd==password:
        print('Access Granted!\n')
        global Dict
        if Dict=={}:
            DB.insert(Document(Dict),doc_id=1)
            Dict=DB.get(doc_id=1)
            menu()
        else:
            menu()
    else:
        print('Wrong Password!\n')
        authenticator()
C] The whole program is menu driven by a while loop under a function menu(). I intended to save the dictionary into the database when the while loop's condition is made false and then kill the program.

btw. this menu() function is called from the authenticator() function
C1] this is the whole menu() function. pls note that the other functions doesn't modify the database in any way. they would process only the dictionary Dict.
[sorry for the insanely long code Big Grin I'm just a beginner.]
def menu():
    opt='y'
    while(opt in 'Yy'):
        print(">-- Contact Management System Menu --<")
        print()
        print('1 = Add entries')
        print('2 = Display Entries')
        print('3 = Search Phone number By Name')
        print('4 = Search Name by Phone Number')
        print('5 = Delete a Contact')
        print('6 = Update phone number of an Existing contact')
#print('7 = Change Password')
        print('Any other Character other than 1, 2, 3, 4, 5 & 6 = Exit Program' )
        Ch=input('Enter your Choice:')
        if Ch=='1':
            add()
            print()
        elif Ch=='2':
            if Dict == {}:
                print('Nothing saved in the PhoneBook!!!!')
            else:
                display()
                print()
        elif Ch=='3':
            print()
            searchbyname()
            print()
        elif Ch=='4':
            print()
            searchbynumber()
            print()
        elif Ch=='5':
            print()
            delete()
            print()
        elif Ch=='6':
            print()
            update()
            print()
        else:
            print('Program Terminated! Window will Close in 4 Seconds.')
            DB.update(Dict, doc_id=1)
            time.sleep(4) # time is already imported
            break
        opt=input('Enter y to continue - or else - enter any other character to terminate program:')
        print()
    else:     #while loop else
        print('Program Terminated! Window will Close in 4 Seconds.')
        DB.update(Dict, doc_id=1)
        time.sleep(4)
sry just realized i reposted the same post Confused
(Feb-05-2021, 10:03 AM)adithya_like_py Wrote: [ -> ]sry just realized i reposted the same post Confused
You also started new thread unnecessarily. I merged your previous thread into this one