Gaurav Bahadur
Gaurav Bahadur

Reputation: 189

updated dictionary fails to recognize the newly added key when program is executed again

I am creating a program which will give the password for any account which is already in the dictionary and if the account is not there,it will ask the user to input the password so that it can save for future use.

Though the program updates the dictionary(last print in the else proves that), but when I again run the program, it doesn't recognize the account which i just added.

password = {
    'a': 'password of a',
    'b': 'password of b',
    'c': 'password of c'
}

inp = input("Enter the username ")

if inp in password:
    print("your password is ",password[inp])

else:
   print("your account is not present\n")
   new_password = input("Enter the password for ")
   password.update({inp : new_password})
   print("Hopefully the list is updated ",password)

for ex. if my inp=d, it will tell me that account is not there and then ask for the input,it shows the dictionary is updated

{'a': 'a ka password', 'b': 'b ka password', 'c': 'c ka password', 'd': 'password of d'}

but next time when i run the program it fails to recognize .

Enter the username d
your account is not present

Upvotes: 0

Views: 34

Answers (2)

That's because your dictionary with accounts is in memory only while the program is running. Once it ends, the dictionary is gone and created from scratch when you run your program again. You need to save it to disk to preserve your updates, and one approach would be using pickle:

init_accounts.py

import pickle

password = {
    'a': 'password of a',
    'b': 'password of b',
    'c': 'password of c'
}

# SAVE THE DATA
with open("data.pickle", "wb") as file:
    pickle.dump(password, file, pickle.HIGHEST_PROTOCOL)

add_account.py

import pickle

# LOAD THE DATA
with open("data.pickle", "rb") as file:
    password = pickle.load(file)

inp = input("Enter the username ")

if inp in password:
    print("your password is ", password[inp])

else:
    print("your account is not present\n")
    new_password = input("Enter the password for ")
    password.update({inp : new_password})

    # SAVE THE DATA
    with open("data.pickle", "wb") as file:
        pickle.dump(password, file, pickle.HIGHEST_PROTOCOL)

    print("Hopefully the list is updated ", password)

Upvotes: 1

rushinstuffin
rushinstuffin

Reputation: 73

Unless I'm missing something, you cannot store data in this way. Once you end the script/close the program, the user input is lost. One way to store the data would be to keep a dictionary in another file and read and write to it.

Upvotes: 0

Related Questions