Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python find object in a list

I have a list of people:

[
    {'name' : 'John', 'wins' : 10 },
    {'name' : 'Sally', 'wins' : 0 },
    {'name' : 'Fred', 'wins' : 3 },
    {'name' : 'Mary', 'wins' : 6 }
]

I am adding wins using a list of names (['Fred', 'Mary', 'Sally']). I don't know if the name is in the list of people already, and I need to insert a new record if not. Currently I'm doing the following:

name = 'John'
person = None
pidx = None
for p in people_list:
    if p['name'] == name:
        person = p
        pidx = people_list.index(p)
        break
if person is None:
    person = {'name' : name, 'wins' : 0}
person['wins'] += 1
if pidx is None:
    people_list.append(person)
else
    people_list[pidx] = person

Is there a better way to do this with a list? Given that I'm saving this to MongoDB I can't use a dict as it will save as an object and I want to use native array functions for sorting and mapping that aren't available for objects.

like image 222
Josh K Avatar asked Feb 25 '11 17:02

Josh K


People also ask

How do you find a specific object in a list Python?

To find an object in a list of objects: Use a generator expression to iterate over the list. Check if each object has an attribute that meets a condition. Use the next() function to return the first matching object.

How do you check if something is in a list in Python?

count() to check if the list contains. Another built-in method in Python, count() returns the number of times the passed element occurs in the list. If the element is not there in the list then the count() will return 0. If it returns a positive integer greater than 0, it means the list contains the element.


1 Answers

I'm assuming here that you don't want to use any structure other than the list. Your code should work, although you unnecessarily write the dictionary back to the list after updating it. Dictionaries are copied by reference, so once you update it, it stays updated in the list. After a little housekeeping, your code could look like this:

def add_win(people_list, name):
    person = find_person(people_list, name)
    person['wins'] += 1

def find_person(people_list, name):
    for person in people_list:
        if person['name'] == name:
            return person
    person = {'name': name, 'wins': 0}
    people_list.append(person)
    return person
like image 174
DzinX Avatar answered Oct 12 '22 00:10

DzinX