I have the following list of dictionaries:
JavaScript
x
2
1
[{'id': 360004373520, 'value': something1}, {'id': 360004411159, 'value': something2}, {'id': 360004373540, 'value': something}]
2
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:
JavaScript
1
11
11
1
lst = [
2
{"id": 360004373520, "value": "something1"},
3
{"id": 360004411159, "value": "something2"},
4
{"id": 360004373540, "value": "something"},
5
]
6
7
to_search = 360004411159
8
9
value = next(d["value"] for d in lst if d["id"] == to_search)
10
print(value)
11
Prints:
JavaScript
1
2
1
something2
2
Or: If you search multiple times, it’s worth considering transforming the list to dictionary:
JavaScript
1
6
1
to_search = 360004411159
2
3
4
dct = {d["id"]: d["value"] for d in lst}
5
print(dct[to_search])
6