0 votes

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"]
in Engine by (39 points)

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.")

1 Answer

+1 vote
Best answer

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...

by (10,690 points)
selected by

I see. Thanks!

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.