我正在尝试使用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"
。有没有办法只删除用户给出的信息?
发布于 2021-09-25 18:17:09
将值设置为None
是您想要的,而不是删除条目。
将del
行替换为以下内容。
account5["Name"], account5["Username"], account5["Password"] = None, None, None
发布于 2021-09-25 19:18:13
为了避免多次遍历列表来查找匹配的帐户,我建议构建一个将名称映射到每个帐户的字典,并使用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
https://stackoverflow.com/questions/69328527
复制相似问题