Home > Enterprise >  How am I able to fix this code when I try to add a dictionary key and value
How am I able to fix this code when I try to add a dictionary key and value

Time:06-10

I am having trouble with one bit of my game where I move nested dictionaries from one to another. This is my code so far

player_inventory_weapons = {
"0": {"Name ": "Basic sword", "Sharpness": 10, "Fire level": 0, "Poison": 0, "Resistance 
addition": 5, "type": "weapons"}   
}

player_equip_weapons = {   

}

# move item from one dicionary to another

def equip():
    inp = str(input("What item would you want to move over? ")) # input number that is the key of what you are trying to equip
    if inp in player_inventory_weapons:
        del player_equip_weapons  #only one allowed at a time
        player_equip_weapons[inp] = player_inventory_weapons[inp]
        del player_inventory_weapons[inp]
equip()

When I try to equip the 'Basic sword" by inputting '0', it gives me the error 'UnboundLocalError: local variable 'player_equip_weapons' referenced before assignment' I've already tried multible things but none of them have worked! If you can help that that would be greatly appreciated.

CodePudding user response:

Don't delete the variable, just empty the dictionary with the clear() method.

def equip():
    inp = input("What item would you want to move over? ") # input number that is the key of what you are trying to equip
    if inp in player_inventory_weapons:
        player_equip_weapons.clear()  #only one allowed at a time
        player_equip_weapons[inp] = player_inventory_weapons[inp]
        del player_inventory_weapons[inp]

Although I'm not sure why you would use a dictionary if it can only have one item at a time. Just make the variable hold the item.

CodePudding user response:

This is your basic problem:

del player_equip_weapons  # This line deletes the variable
player_equip_weapons[inp] = player_inventory_weapons[inp]  # This line tries to access a variable that doesn't exist

Because you're deleting the variable, your attempt to access it will fail.

Note that you almost never want to use del or global variables. Rather, do something like this:

def equip(inventory: dict):
    inp = input("What item would you want to move over? ")
    item = inventory.pop(inp, None)
    if item is not None:
        return {
            "hand": inventory.get(inp, "Nothing")
        }
    else:
        print("No such item in your inventory!")
        return dict()

player_equipped_weapons = equip(player_inventory_weapons)

This overwrites the equipped weapons variable with the result of your equip function. In this manner, you don't need to worry about clearing the original dictionary. And rather than use del you can use pop() to remove the item from your inventory data, which lets you then check to see if that item actually existed there.

  • Related