[英]How am I able to fix this code when I try to add a dictionary key and value
我在將嵌套字典從一個移動到另一個的游戲中遇到問題。 到目前為止,這是我的代碼
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()
當我嘗試通過輸入“0”來裝備“基本劍”時,它給了我錯誤“UnboundLocalError: local variable 'player_equip_weapons' referenced before assignment' 我已經嘗試了多種方法,但都沒有奏效!如果可以幫助,將不勝感激。
不要刪除變量,只需使用clear()
方法清空字典。
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]
雖然我不確定如果字典一次只能包含一個項目,為什么你會使用它。 只需讓變量保存該項目。
這是您的基本問題:
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
因為您正在刪除該變量,所以您訪問它的嘗試將失敗。
請注意,您幾乎從不想使用del
或全局變量。 相反,請執行以下操作:
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)
這會用您的裝備功能的結果覆蓋裝備的武器變量。 通過這種方式,您無需擔心清除原始字典。 而不是使用del
您可以使用pop()
從庫存數據中刪除該項目,然后您可以檢查該項目是否確實存在於那里。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.