Tom
Tom

Reputation: 9643

python - search for an element inside a dictionary inside a list

My data structure looks like this:

  - testSet: a list of records in the test set, where each record
             is a dictionary containing values for each attribute

And in each record there is an element named "ID". I now want to search for a record inside testSet by an ID value. So when I'm given an ID = 230 I want to return the record that it's ID element equals 230.

How can I do that?

Upvotes: 0

Views: 153

Answers (3)

Michel Keijzers
Michel Keijzers

Reputation: 15347

E.g.:

set = [{'ID': 50}, {'ID': 80}]

def find_set(id):
    return [elem for elem in set if elem['ID'] == id]

This will return all items with the specified ID. If you only want the first one, add [0] (after checking if it exists, e.g.:

def find_set(id):
    elems = [elem for elem in set if elem['ID'] == id]
    return elems[0] if elems else None

Upvotes: 0

msvalkon
msvalkon

Reputation: 12077

Something like this?

for record in testSet:
    if record['ID'] == 230:
        return record

Upvotes: 2

jamylak
jamylak

Reputation: 133504

next((x for x in testSet if x["ID"] == 230), None)

This will return the first item with that ID or None if it's not found.

Upvotes: 5

Related Questions