What is the most efficient way to search a dictionary in an array of dictionaries?

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

Suppose I have this array of dictionaries:

var fruits = [{
               "name" : "apple",
               "color" : "red",
              },
              { 
               "name" : "banana",
               "color" : "yellow"
                }
               #more dictionaries of fruits and their color
                ]
          

What would be the most efficient way to find, say, the color of the fruit “banana”? Is iterating over the list the only way?

var color
for fruit in fruits:
   if(fruit["name"] == "banana"):
       color = fruit["color"]
       break

For the most part, you have to iterate over the dictionary to find what you want. If you know exactly what you want, though, you can use the has() method to check for a key:

 # Check the dictionary "foo" for the desired key.
 if foo.has("bar"):
      print("It has bar.")

Ertain | 2020-08-17 17:25

:bust_in_silhouette: Reply From: jgodfrey

Yep, at its core, I think that’s probably about the best you can do. Though, if you’re doing much of this kind of thing, I might wrap up the functionality into a utility function for reusability…

I see. Thanks!

godotnoobperson | 2020-08-17 17:17

:bust_in_silhouette: Reply From: fergicide

Here’s a way of efficiently searching entity properties using dictionaries – if classes are going to be overkill.

# Fruit properties
const COLOR := { RED = "red", YELLOW = "yellow", YELLOW_ORANGE = "yellow orange" }
const SHAPE := { ROUND = "round", CURVED = "curved" }
const TEXTURE := { HARD = "hard", SOFT = "soft" }

# Fruits
const fruits: Dictionary = {
	APPLE = {
		COLOR = COLOR.RED,
		SHAPE = SHAPE.ROUND,
		TEXTURE = TEXTURE.HARD
	},
	BANANA = {
		COLOR = COLOR.YELLOW,
		SHAPE = SHAPE.CURVED,
		TEXTURE = TEXTURE.SOFT
	},
	PEACH = {
		COLOR = COLOR.YELLOW_ORANGE,
		SHAPE = SHAPE.ROUND,
		TEXTURE = TEXTURE.SOFT
	}
}

func _ready() -> void:
	# Find color of a particular fruit
	# Very efficient dictionary lookup.
	prints("Color of banana is:", fruits.BANANA.COLOR)
	
	# Find all 'round' fruits
	# Inefficient as it needs to scan a complete array of fruits.
	for fruit in fruits:
		var property = fruits[fruit]
		if property.SHAPE == SHAPE.ROUND:
			prints(fruit, property.COLOR, property.SHAPE, property.TEXTURE)
	
# ----- Output -----
# Color of banana is: yellow
# APPLE red round hard
# PEACH yellow orange round soft