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?

Answers


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


Need Your Help

In Python threading, how I can I track a thread's completion?

python multithreading

I've a python program that spawns a number of threads. These threads last anywhere between 2 seconds to 30 seconds. In the main thread I want to track whenever each thread completes and print a mes...

CASE expressions on datetime columns

sql sql-server tsql

I'm trying to access a datetime column to find out whether the date is within a week from today, or overdue. Then write a new column's value to say Incoming, Overdue or Fine.