Python - testing if an object attribute is equal to a given value
Say you have a list of people.
class Person: def __init___(self, name, id): self.name = name self.id = id people =  for x in xrange(0,100) #find people and append to people list
Now, I have a list of people objects. How could I most efficiently find, say, a person whose name is "Bob" from the people list?
With just a list and no other indices, you have to use a list comprehension:
matching = [p for p in people if p.name == 'Bob']
but if you have to do that a lot, you may want to create an index:
from collections import defaultdict nameindex = defaultdict(list) for person in people: nameindex[person.name.lower()] = person nameindex['bob'] # a list of people named Bob.
This way you only have to loop through all your people once (cost O(N)), after which any name lookup has constant cost (O(1)).