Find a value in an array of dictionaries

Godot Version 4.3

I have an array of dictionaries to represent enemy information. So for example:

enemy_dictionary = [{“class”: “fighter”, “location”: (0,3)}, {“class”: “ranger”, “location”: (3,4)}]

To find a value in the dictionary do I need to do a for loop on the array with the dictionary key each time or is there a simpler way?

I’ve tried:

if enemy_dictionary.has(0,3):

but it returns false even though (0,3) is in the array above

thanks

You can’t just do if enemy_dictionary.has(0,3): if you want to search for values inside the dictionaries in the array. You have to get each dictionary first and check its values. Your approach will only work if you check if the array contains a dictionary, not the values inside the dictionary.

The solution you’re looking for is:

var enemy_dictionary: Array[Dictionary] = \
[
	{"class": "fighter", "location": [0,3]},
	{"class": "ranger", "location": [3,4]}
]
	
func _ready():
	check_if_array_of_dict_has_value([2,4])

func check_if_array_of_dict_has_value(value):
	var value_found: bool = false
	
	for dict: Dictionary in enemy_dictionary:
		if dict.values().has(value):
			value_found = true
			break
	
	if value_found: 
		print("I found ", value)
	else:
		print("Cannot find ", value)

Note that if you have multiple dictionaries with the same values, it will only check for one, which is the first one and stop searching.

1 Like

Where have the dicts been defined?

The value of dict are each dictonaries in the array you are looping through.

yeah that’s exactly what I ended up doing. I didn’t know if there was an easy way to search vs. looping through the for dict: statement. thanks for the help!

1 Like