Updating dictionary (Invalid get index '103' (on base: 'Dictionary')

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By AltoWaltz

I have one dictionary for inventory items:

print(DataImport.inven_data)

{101:[Shield_Beastmaster, 1], 102:[Helmet_Footman, 1], 103:[Shield, 1], 104:[Helmet_Beastmaster, 1], 105:[Shield_Beastmaster, 1], 106:[Shield, 1], 201:[Mace, 1], …other items…, 209:[Bow, 1], …other items… 501:[Iron_Ingot, 1], 502:[Iron_Ingot, 1], …other items…, Gold:719, HealthPack:5 }

And other dictionary for true false booleans checking it item is in the dictionary:

print(SaveData.wearables_dic)

{Helmet_Beastmaster:True, Helmet_Footman:True, Helmet_Knight:False, Shield:True, Shield_Beastmaster:True, Shield_Footman:False, Shield_Knight:False}

I am updating true false dictionary through the series of if checks on new loot. I know it can probably be done much more efficient but I am new to Godot so I like to have code that I am able to understand. The problem arises when I delete item from the dictionary where I tried with:

if InvenData["101"][0] != "Shield" and InvenData["102"][0] != "Shield" and InvenData["103"][0] != "Shield":
	SaveData.wearables_dic["Shield"] = false

And got: Invalid get index ‘103’ (on base: ‘Dictionary’), as 103 is at that moment already deleted from the dictionary.

Ok, so I tried with:

if InvenData.has(["103"][0]):
	if InvenData["101"][0] != "Shield" and InvenData["102"][0] != "Shield" and InvenData["103"][0] != "Shield"":
	SaveData.wearables_dic["Shield"] = false

Error is now handled, but true false boolean still does not get updated, because that item just got deleted, so it never runs through the nested if. Any idea how to handle this ? Any help appreciated.

turned comment into the answer below

Bernard Cloutier | 2020-10-01 15:02

:bust_in_silhouette: Reply From: Bernard Cloutier

I know it can probably be done much more efficient but I am new to Godot so I like to have code that I am able to understand.

Code you can understand >>>>>>>>>>> efficient code. Regardless of whether you are new or not! Only if you start having noticeable frame drops should you start to worry about efficiency.

Try replacing your last snippet of code with this:

var has_shield = false
for key in ["101", "102", "103"]:
    if InvenData.has(key) and InvenData[key][0] == "Shield":
        has_shield = true
SaveData.wearables_dic["Shield"] = has_shield 

Thank you a lot.

AltoWaltz | 2020-10-02 07:29