Skip to content
Advertisement

Best practice/way to get value where id = something on a list of dictionaries

I have the following list of dictionaries:

[{'id': 360004373520, 'value': something1}, {'id': 360004411159, 'value': something2}, {'id': 360004373540, 'value': something}]

I would like to get the value where id = xxxxxxxxxxxx.

Which would be the fastest way?

Advertisement

Answer

One possible solution is to use next() built-in method:

lst = [
    {"id": 360004373520, "value": "something1"},
    {"id": 360004411159, "value": "something2"},
    {"id": 360004373540, "value": "something"},
]

to_search = 360004411159

value = next(d["value"] for d in lst if d["id"] == to_search)
print(value)

Prints:

something2

Or: If you search multiple times, it’s worth considering transforming the list to dictionary:

to_search = 360004411159


dct = {d["id"]: d["value"] for d in lst}
print(dct[to_search])
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement