Topic was automatically imported from the old Question2Answer platform.
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.")
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…