首页 > 解决方案 > 即使重新运行代码,如何在 python 中更新列表和字典?

问题描述

我目前正在为应用程序创建一个注册和登录页面,但是每当我创建一个新的用户名/密码组合时,我都会在创建它后立即在我的列表中看到它(我在程序末尾打印字典以便我可以看到它)但是在我决定重新运行代码之后,我刚刚创建的用户名和密码就消失了。即使重新运行代码,如何让这些保持不变?

我不知道添加我的代码是否会有所帮助(我认为不会),但我会添加我认为可能最有帮助的部分:

import re

usernames_passwords = {'lmaoidontknow': 'password123',
                   'evillover456': 'waterworld332',
                   'xyzitsme': 'notmypass',
                   'unicornpops': 'blahbleh76'}

while not chosen_user:
        chosen_user = input("""Enter the username that you would like. Please keep it between 6 and 15 
        characters. Do not use special characters such as '&', '@', or '!' in your username. Underscores are 
        allowed.\n>""")
        if (6 <= len(chosen_user) <= 15) and re.search(r"^[a-zA-Z0-9_]+$", chosen_user):
            print('')
        else:
            print('Username does not meet the requirements. Please try again.')
            chosen_user = False
        if chosen_user in input_usernames:
            print('This username is already taken. PLease try again.')
            chosen_user = False

创建顶部的字典只是为了测试某些事情,例如确保用户名没有被复制并且它们不是永久的。每当我重新运行我的代码时,该字典是唯一保留的用户名/密码,我希望保留我输入的所有用户名和密码。

编辑:这只是用户名代码。如果要求,可以包含密码代码,但我认为这不会有太大的不同。

标签: pythonlistdictionary

解决方案


当您使用硬编码字典时,它的数据在您重新运行服务器时不会持久化,您需要使用 db 来存储并使其持久化。


推荐阅读