Home > Blockchain >  How to delete one value of keys from dictionary?
How to delete one value of keys from dictionary?

Time:09-26

I'm trying to delete a specific input of user using del function but it deletes the whole key values below it

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

After the user confirms the deletion, it deletes all values in the dictionary and gives a key error: "name". Is there any way to delete only the information given by the user?

CodePudding user response:

Setting the values to None is what you want instead of deleting the entries.

Replace the del line with this.

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

CodePudding user response:

To avoid having to loop through the list multiple times to find the matching account, I suggest building a dict that maps the name to each account, and using accounts.remove() to remove the account.

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
  • Related