再次执行程序时,更新的词典无法识别新添加的键

时间:2018-10-21 06:17:08

标签: python python-3.x dictionary

我正在创建一个程序,该程序将为词典中已经存在的任何帐户提供密码,如果该帐户不在该帐户中,它将要求用户输入密码,以便将来保存。

尽管程序更新了词典(else的最后打印证明),但是当我再次运行该程序时,它无法识别我刚刚添加的帐户。

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)

例如如果我的inp = d,它会告诉我该帐户不在那里,然后要求输入,它表明字典已更新

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

但是下次我运行程序时,它无法识别。

Enter the username d
your account is not present

2 个答案:

答案 0 :(得分:1)

这是因为只有在程序运行时,带有帐户的字典才在内存中。一旦结束,再次运行程序时,字典将消失并从头开始创建。您需要将其保存到磁盘以保留更新,一种方法是使用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)

答案 1 :(得分:0)

除非我丢失了某些内容,否则您不能以这种方式存储数据。一旦结束脚本/关闭程序,用户输入就会丢失。存储数据的一种方法是将字典保存在另一个文件中,并对其进行读写操作。