python - 更新字典的键和值

标签 python python-3.x dictionary

所以我对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!')

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

最佳答案

密码管理始终是一个非常微妙的话题,但由于您刚刚开始并且不会询问安全性,所以让我们看看如何以非常简单的方式加载和编写一个简单的 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 中实现它,而不会增加太多复杂性。但在这种应用程序中,您很快就会感到需要更实用和更强大的东西。例如,随着数据库的增长,将整个数据库加载到内存中可能开始变得不切实际。它可能会引发更多的安全问题。

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

关于python - 更新字典的键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52735995/

相关文章:

python - 如何在没有拆分器的情况下拆分等长字符串并扩展数据帧

python - 尝试访问命令行变量时出现 Pytest KeyError

python - Pandas 在有条件的情况下找到单个值

python - 给定一个 Unicode 代码点列表,如何将它们拆分为 Unicode 字符列表?

dictionary - 为什么 Julia 的 Dict{String, Any} 不接受 'any' 值

python - 在Python中分割字典并将其写入不同的csv文件

python - 使用 numpy 在 Pygame 中进行更高效的风洞模拟

python - 如何在python中安装模块和包

python - 如何在tkinter中将 'text'按钮彼此进行比较?

python - 如何通过添加其他表中的对象来操作Python字典