Invalid get index on base array (Dictionary)

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

I’m currently working on a crafting system for my game. I have two dictionaries: one for the hotbar and one for the inventory. I combined them info another dictionary to loop through all items that player has to search for ingredients for crafting (which is also a dictionary).
Here’s the code:

var all_items = {}
all_items = PlayerInventory.inventory.values() + PlayerInventory.hotbar.values()

for item in all_items:
		if all_items[item][0] == ing_1 and all_items[item][1] >= ing_1_amount:
			has_first_ing = true
			inv_amount_1 = all_items[item][1]
		elif all_items[item][0] == ing_2 and all_items[item][1] >= ing_2_amount:
			has_second_ing = true
			inv_amount_2 = all_items[item][1]

When I try to craft something I get an error of invalid index. For example, if i have a stone in the inventory the error says “Invalid get index ‘[stone, 1]’ (On base: Array)”.

I tried to do the same thing with only the inventory dictionary and everything worked fine.
The code:

		for item in PlayerInventory.inventory:
		if PlayerInventory.inventory[item][0] == ing_1 and PlayerInventory.inventory[item][1] >= ing_1_amount:
			has_first_ing = true
			inv_amount_1 = PlayerInventory.inventory[item][1]
		elif PlayerInventory.inventory[item][0] == ing_2 and PlayerInventory.inventory[item][1] >= ing_2_amount:
			has_second_ing = true
			inv_amount_2 = PlayerInventory.inventory[item][1]

These ing_1 and ing_2 are just shortcuts for ingredients[0] and ingredients[1]

var ing_1 = ingredients[0][0]
var ing_1_amount = ingredients[0][1]
	
var ing_2 = ingredients[1][0]
var ing_2_amount = ingredients[1][1]

I’m pretty sure that the problem has something to do with syntax but i can’t be sure.
I would be really grateful if anyone could help me with this problem.

:bust_in_silhouette: Reply From: exuin
all_items = PlayerInventory.inventory.values() + PlayerInventory.hotbar.values()

This line gets you an Array, not a Dictionary. You’re replacing the original dictionary with an array.

for item in all_items:

This line iterates through each item in the array. So all_items[item][0] will not work since it’s an array and not a dictionary.

This line gets you an Array, not a Dictionary. You’re replacing the original dictionary with an array.

How can i make this as a dictionary then?

misuki | 2021-04-22 22:08

There’s no easy way. You’ll have to duplicate one of the dictionaries and then iterate through the other and assign each key-value pair in a for loop. Or just store them all in one dictionary.

exuin | 2021-04-22 22:14