Say I have a list of dictionaries:
universe_creatures = [
{'type': 'dragon', 'weight': 1400},
{'type': 'kraken', 'weight': 6000},
{'type': 'elf', 'weight': 75},
...]
How can I search if there’s a certain type in one of the dictionary values in a shortly phrased code, but as efficient as possible?
What I currently have:
typ = 'dragon'
found = False
I believe for-loop is the most efficient because it iterates over once, and doesn’t have overheads as generator calls do.
# for loop
for c in universe_creatures:
if typ == c['type']:
found = True
But I’m looking for a shorter phrase, like the two below, and want to learn if the generator expression is too expensive compared to the for-loop above, since I think it is more efficient than list comprehension as the latter iterates over data more than once.
# generator expression
found = typ in (c['type'] for c in universe_creatures)
# list comprehension
found = typ in [c['type'] for c in universe_creatures]