Search code examples
pythonlistdictionaryuser-input

Delete value from Dictionary


players = {
        "nome": "",
        "score": [] 
    }

cancel = False
player_list = []

while (True):
    name = input("Insert player name: ")

    player_list.append({
        "Player Name": name
    })

    cont = input("Do you wish to add another player? (Y/N)")
    if cont == "N":
        break;

print("Player List: ", player_list)

while (True):
    eliminate_player = input("Select player to delete: ")

    player_list.pop({
        "Player Deleted": eliminate_player
    })    

print ("Updated List", player_list)

Hello everyone! Im having some trouble deleting an entry from my player list using user input. Im getting the error:'dict' object cannot be interpreted as an integer but I can't seem to find what is wrong because Im using similar method I used to add players and it worked fine.

Any ideas?


Solution

  • You are not using the right method. pop(n) requires an integer (index) to remove the given index from the list. You should use remove().

    remove() is an inbuilt function that removes a given object from the list. It does not return any value.

    Syntax:
    
    list_name.remove(obj) 
    

    Try this:

    player_list.remove({"Player name": eliminate_player})
    

    If the element doesn't exist, it throws ValueError: list.remove(x): x not in list exception. Wrap it in try catch clause in Python.

    Note:

    remove() removes the first occurrence of the object from the list.

    To remove all occurence of your Player:

    while (player_list.count({"Player name": eliminate_player})): 
        player_list.remove({"Player name": eliminate_player}) 
    

    See this to understand the difference between pop, remove and del on lists.

    How can I stop it after deleting one player and then show the updated list?

    You can use count method to break from the while loop:

    while (True):
        eliminate_player = input("Select player to delete: ")
    
        di = {"Player name": eliminate_player}
        if player_list.count(di):
            player_list.pop(di)
            break