【问题标题】:How to delete one value of keys from dictionary?如何从字典中删除一个键值?
【发布时间】:2021-11-18 12:51:36
【问题描述】:

我正在尝试使用 del 函数删除用户的特定输入,但它会删除它下面的整个键值

for account3 in accounts:
    print("\t   ", account3["Name"].ljust(25), account3["Username"].ljust(27), account3["Password"])

    userinput = input('Account Name you want to delete: ')
    for account4 in accounts:
        if userinput == account4["Name"]:
            userinput = input('Re-enter name to confirm: ')

            for account5 in accounts:
                if userinput == account5["Name"]:
                    del account5["Name"], account5["Username"], account5["Password"]
                    print('Deleted Successfully!')
                    menu()
                    break

用户确认删除后,删除字典中的所有值,并给出key error: "name"。有没有办法只删除用户提供的信息?

【问题讨论】:

  • 您希望密钥本身保留但价值消失?只需将值设置为None 然后...当您可以在字典中进行键查找时,您的循环也过于复杂。
  • 我正在尝试从用户输入中删除一组信息,但其他用户输入将保留。只有被选中的会去。这就是试图做的先生

标签: python dictionary del


【解决方案1】:

将值设置为 None 是您想要的,而不是删除条目。

用这个替换del 行。

account5["Name"], account5["Username"], account5["Password"] = None, None, None

【讨论】:

  • 给出一个错误 NoneType
  • 这是更改该确切行的方法。正如我已经指出的那样,您的循环不必要地复杂。您也没有向我们展示代码的数据结构或其他相关部分。因此,它可以为您提供标准答案,而不是针对您的问题量身定制的答案。
【解决方案2】:

为避免多次遍历列表以找到匹配的帐户,我建议构建一个将名称映射到每个帐户的字典,并使用 accounts.remove() 删除该帐户。

accounts_by_name = {account["Name"]: account for account in accounts}

for account in accounts:
    print("\t   ", account3["Name"].ljust(25), account3["Username"].ljust(27), account3["Password"])
    name = input("Account name you want to delete: ")
    if name not in accounts_by_name:
        continue
    if input("Re-enter name to confirm: ") != name:
        continue
    accounts.remove(accounts_by_name[name])
    menu()
    break

【讨论】:

  • 代码没有通过,因为我的用户输入字典附加在列表中,accounts= [],我只想删除值,例如我的字典 'john' 中的名称, 'allen' 然后用户想从字典中删除 john。所以当我打印我的字典时,艾伦只会出现在字典中。
  • 也许您可以在问题中包含accounts 的值,并说明您希望在删除帐户后它的样子?由于现有代码不起作用,因此无法从现有代码中推断出所需的行为。
最近更新 更多