首页 > 解决方案 > 更新字典的键和值

问题描述

所以我对python很陌生,几天前开始学习......我遇到了一个练习项目,我们将在其中创建一个存储帐户及其各自密码的密码柜。

#! python3
# pw.py - An insecure password locker program.

PASSWORDS = {'email': 'F7minlBDDuvMJuxESSKHFhTxFtjVB6',
             'blog': 'VmALvQyKAxiVH5G8v01if1MLZF3sdt',
             'luggage': '12345'}

import sys
if len(sys.argv) < 2:
    print('Usage: python pw.py [account] - copy account password')
    sys.exit()

account = sys.argv[1]      # first command line arg is the account name
if account in PASSWORDS:
    pyperclip.copy(PASSWORDS[account])
    print('Password for ' + account + ' copied to clipboard.')
else:
    print('There is no account named ' + account)

这就是代码。PASSWORDS因此,如果该帐户之前不存在,我想到了一种使用新信息更新字典的方法。所以我将这几行代码添加到 else 语句中

    print('Input the password for the said account to update the info.')
    PASSWORDS[account] = input()
    print('Info updated!')

我现在面临的问题是添加到字典中的值在程序完成后不会保留。

标签: pythonpython-3.xdictionary

解决方案


密码管理始终是一个非常微妙的话题,但是由于您才刚刚开始并且没有询问安全性,让我们看看我们如何以非常简单的方式加载和编写一个简单的 JSON 文件。

首先,让我们将实际数据移动到一个单独的文件中,我们可以将其命名为database.json

{"email": "F7minlBDDuvMJuxESSKHFhTxFtjVB6",
 "blog": "VmALvQyKAxiVH5G8v01if1MLZF3sdt",
 "luggage": "12345"}

然后我们像这样更改应用程序代码:

#!/usr/env python3
"""
 pw.py - An insecure password locker program.
"""
import sys
import pyperclip
import json
import os


# The path to the database file
DB_FILE = "~/Desktop/database.json"


def main():
    if len(sys.argv) < 2:
        print('Usage: python pw.py [account] - copy account password')
        sys.exit()

    account = sys.argv[1]      # first command line arg is the account name
    db = os.path.expanduser(DB_FILE)
    with open(db) as f:
        data = json.load(f)  # Load a dictionary for disk

    if account in data:
        pyperclip.copy(data[account])
        print('Password for ' + account + ' copied to clipboard.')
    else:
        print('There is no account named ' + account)
        print('Input the password for the said account to update the info.')
        new_passwd = {account: input()}  # create a dictionary with the new account data
        data.update(new_passwd)  # update the main dictionary with the new data

        with open(db, 'w') as f:
            json.dump(data, f)  # convert to JSON and write to disk

        print('Info updated!')


if __name__ == "__main__":
    main()

对于这样一个简单的任务,您可以使用多种文件格式。JSON 是一种以既合乎逻辑又易于理解的方式映射到 Python 字典的格式,但您也可以在 CSV 中实现它,而不会增加太多复杂性。但是在这种应用程序中,您很快就会感觉到需要更实用和更强大的东西。例如,随着数据库的增长,将整个数据库加载到内存中可能开始变得不切实际。它可能会引发更多的安全问题。

花点时间学习这些基础知识,然后探索该模块sqlite。它允许在单文件关系数据库中使用 SQL,并将为强大的应用程序和进一步学习铺平道路。


推荐阅读