Reputation: 13
I want to update the keys and values in my dictionary permanently, I have a dictionary stored in a variable, which has now 2 keys and values, I want to add keys and values, by input, and want them to be stored in the dictionary forever, even if I restart the program, What happens now is The keys and values given by the user are inserted successfully into the dictionary, but as soon as I restart the program, It is again back to the 2 values which I gave in the program.
Code:
mails = {'robin': '[email protected]', 'michael': '[email protected]'}
cont_name = input('Enter the contact name: ') {Jessey}
cont_mail = input('Enter the mail-id: ') {[email protected]}
dict1 = {cont_name:cont_mail}
mails.update(dict1)
print (mails)
(This gives me correct output)
Output: {'robin': '[email protected]', 'michael': '[email protected]', 'Jessey': '[email protected]'}
but as soon as I Restart my program, and print the dictionary (mails), it shows me this output:
{'robin': '[email protected]', 'michael': '[email protected]'}
Answers would be appreciated, Thanks in Advance!
Upvotes: 1
Views: 426
Reputation: 62
I guess pickle is a good solution for this.
import pickle, os
def load_emails(mail_file):
if os.stat(mail_file).st_size == 0:
return {}
mails = pickle.load(open(mail_file, 'rb'))
return mails
def store_emails(mails, mail_file):
pickle.dump(mails, open(mail_file, 'wb'))
mail_file = "userdata"
mails = load_emails(mail_file)
cont_name = input('Enter the contact name: ')
cont_mail = input('Enter the mail-id: ')
mails[cont_name] = cont_mail
store_emails(mails, mail_file)
You need to call the store_emails()
function every time you add a new key to the dictionary.
Upvotes: 0
Reputation:
Variables in Python are temporary. If you want them to be permanent, you could store the data in a JSON file or in your database. Or you could use Daweo's method, which I recommend, where you use shelve
, a built-in Python module.
Upvotes: 1
Reputation: 36440
want them to be stored in the dictionary forever, even if I restart the program
You need what is called data persistence, you can use built-in shelve module for that. Consider following simple example which provide favorite color of user if known otherwise ask for one and save it
import shelve
d = shelve.open("userdata")
name = input("What is your name?")
if name in d:
print("Your favorite color is", d[name])
else:
color = input("What is your favorite color?")
d[name] = color
d.close()
where userdata is name of file where data are stored.
Upvotes: 0