Python Forum
[for a h/w project] How to save and get back dictionary in a .json file in TinyDB.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[for a h/w project] How to save and get back dictionary in a .json file in TinyDB.
#1
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
Reply
#2
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.
Reply
#3
Bug 
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)
Reply
#4
sry just realized i reposted the same post Confused
Reply
#5
(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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  dictionary output to text file (beginner) Delg_Dankil 2 1,187 Jul-12-2023, 11:45 AM
Last Post: deanhystad
  Storing version of the downloaded libs using json file Rakshan 3 1,330 Mar-21-2023, 07:50 AM
Last Post: buran
  Using dictionary to find the most sent emails from a file siliusu 6 7,588 Apr-22-2021, 06:07 PM
Last Post: siliusu
  Updating dictionary in another py file tommy_voet 1 4,893 Mar-28-2021, 07:25 PM
Last Post: buran
  Making a dictionary from a file instyabam 0 1,509 Oct-27-2020, 11:59 AM
Last Post: instyabam
  how can i create a dictionary of dictionaries from a file Astone 2 2,262 Oct-26-2020, 02:40 PM
Last Post: DeaD_EyE
  Convert all actions through functions, fill the dictionary from a file Astone 3 2,444 Oct-26-2020, 09:11 AM
Last Post: DeaD_EyE
  Extracting link list to json file naor 5 2,626 Sep-17-2020, 04:16 PM
Last Post: micseydel
  Parse text from a .txt file and save multiple output .txt rattlerskin 10 11,089 Aug-25-2019, 08:50 PM
Last Post: dwirsig
  Using Pandas to save csv file into mysql database with for loop kirito85 4 3,437 Feb-05-2019, 01:13 AM
Last Post: kirito85

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020