Search code examples
pythondictionaryshelve

How could new items be saved in a dat file which are added by the user?


There's a dictionary with 3 pairs of fruits in 2 languages. One of them is not correct in English (pomme - aple) which can be fixed by user. Also, user can add new words to the dictionary in 2 languages. User can quit the dictionary if doesn’t want to add new fruit or fix the wrong one. The new or fixed words should be saved in a dat file, but the file remains empty :( It’s a homework and I have to solve this problem with shelve, but I don’t know how. Here is my attempt:

import shelve
store = shelve.open("fruits.dat")
try:
    mydict = store["allfruits"]
except:
    mydict = {"pomme" : "aple", "poire" : "pear", "cerise" : "cherry"}

mydict = {"pomme" : "aple", "poire" : "pear", "cerise" : "cherry"}
while True: 
    answer=input("Write a fruits name ")
    if answer == "pomme":
        print(mydict["pomme"])
        answer1=input("Would you like to change it? ")
        if answer1 == "yes":
            newworld=input("What's that? ")
            mydict2 = {"pomme" : newworld}
            mydict.update(mydict2)
            anotherfruit=input("Thx. Are you interested in another fruits name? ")
            if anotherfruit=="yes":
                continue
            else:
                print("Bye")
                break
        else:
            print("Bye")
            break
    elif answer not in mydict:
        adding=input("It's not in there. Would you like to add? ")
        if adding == "yes":
            newworld1=input("How is it in English? ")
            mydict3 = {answer : newworld1}
            mydict.update(mydict3)
            anotherfruit=input("Thx. Are you interested in another fruits name? ")
            if anotherfruit=="yes":
                continue
            else:
                print(mydict)
                break
        else:
            print("Bye")
            break

store["allfruits"] = mydict
store.sync()
store.close()

Solution

  • Here -->

    try:
        mydict = store["allfruits"]
    except:
        mydict = {"pomme" : "aple", "poire" : "pear", "cerise" : "cherry"}
    
    mydict = {"pomme" : "aple", "poire" : "pear", "cerise" : "cherry"}
    while True:
        ...
    

    You try to read mydict from the DB with mydict = store['allfruits']. If that fails (in the except: statement) you assign mydict a default value. That part's fine.

    But then immediately after you assign mydict = { ... } again overriding what you just read from the database.