Can't seem to access dictionary keys

Godot Version

4.3 stable Windows 11

Question

I have this code that is supposed to add graphic slots with item sprites in them:

for slotnumber in weapon_slots :
		var slot_graphic = TextureRect.new()
		slot_graphic.texture = load("res://Textures/GUI/inventory_slot.png")
		weapon_inventory.add_child(slot_graphic)
		print(collected_upgrades["weapon"][slotnumber].keys())
		if not collected_upgrades["weapon"][slotnumber].keys().size() == 0 :
			var item_graphic = TextureRect.new()
			item_graphic.texture = load(UpgradeDb[collected_upgrades["weapon"][slotnumber][0]]["icon"])
			print(UpgradeDb[collected_upgrades["weapon"][slotnumber].keys()[0]]["icon"])
			slot_graphic.add_child(item_graphic)

But the keys() function just returns an empty array everytime, even though this is what collected_upgrades looks like:

{ "weapon": { 0: { "hammer": { "level": 1 } }, 1: {  }, 2: {  }, 3: {  }, 4: {  }, 5: {  }, "nonslot": {  } }, "passive": { 0: {  }, 1: {  }, 2: {  }, 3: {  }, 4: {  }, 5: {  }, "nonslot": {  } } }

As far as I can tell, collected_upgrades["weapon"][slotnumber].keys() should return an array with “hammer”, and then empty arrays for the remaining slots for the rest of the for loop. But that doesn’t seem to be what’s happening. Do I just not understand dictionaries? Is my syntax wrong? This is giving me a headache, any help is appreciated.

what in weapon_slots

It’s an integer with a value of 6.

var weapon_slots = [1, 2, 3, 4, 5, 6]

Tried that, and result is the same. Besides, I would like weapon_slots to be an easily modifiable amount that can increase or decrease - it’s just the amount, a stat, and the actual slot information is held in collected_upgrades.

What does the program actually print? What if you print every step along the way

print(collected_upgrades["weapon"])
print(collected_upgrades["weapon"][slotnumber])

I ran this code

func _ready() -> void:
	var collected_upgrades := { "weapon": { 0: { "hammer": { "level": 1 } }, 1: {  }, 2: {  }, 3: {  }, 4: {  }, 5: {  }, "nonslot": {  } }, "passive": { 0: {  }, 1: {  }, 2: {  }, 3: {  }, 4: {  }, 5: {  }, "nonslot": {  } } }
	for slotnumber in 6:
		print(collected_upgrades["weapon"][slotnumber].keys())

and got this result

["hammer"]
[]
[]
[]
[]
[]

So I think the issue is not with your understanding of dictionaries or syntax, but with the contents of the collected_upgrades dictionary. If it’s empty, then maybe whatever code you use to add “hammer” to slot 0 does not work?

1 Like

Thank you, this was the problem! I actually had another player script that extended from the main player script, and the ready function had a super() that ran my update_inventory function BEFORE the subscript had a chance to define the dictionary. I ran the update_inventory() through call_deferred() and it worked.

1 Like