Herodot Thukydides
Herodot Thukydides

Reputation: 147

Searching for an dictionary value inside a list

my method searches for a specific value through a list of dictionaries. I would like to expend it. It should return not only the found dictionary but also the index of the dictionary.

What do I have to modify?

search method

def search_user(self, user_id, data):
        return [element for element in data if element['id'] == user_id]

input data

[
    {
        "id": "12",
        "other": "stuff"
    },
    {
        "id": "987654321",
        "other": "stuff"
    }
]

current return value

# dictionary
{
        "id": "987654321",
        "other": "stuff"
}

target return value

# index of the dictionary, dictionary
[
    1,
    {
        "id": "987654321",
        "other": "stuff"
    }

]

Upvotes: 0

Views: 30

Answers (1)

Arco Bast
Arco Bast

Reputation: 3892

You could use enumerate:

def search_user(self, user_id, data):
    return [(lv, element) for lv, element in enumerate(data) if element['id'] == user_id]

This will return a list of tuples, where the first element of each tuple is the index and the second the dictionary.

Upvotes: 1

Related Questions