Search code examples
pythonjson

Updating Dictionaries permanently in Python


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!


Solution

  • 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.