Say I have a list of dicts where dict['id']
is unique, and I want to access one specific dict.
This is how I would usually do that, more or less.
d_ = [d for d in list_of_dicts where d['id']=='the_id_i_want'][0]
Is there a better/cleaner/more pythonic way to do this?
(edit -- this is an API response, otherwise I'd just make it a dict in the first place)
CodePudding user response:
You can avoid looping over the entire list using a generator to take just the leading value:
d = next(
(d for d in list_of_dicts if d['id'] == 'the_id_i_want'),
None)
Here, if it is not found, d
will be set to None
.
CodePudding user response:
You can use next()
(Note: you can use default=
parameter to specify value to return when dict is not found):
list_of_dicts = [{"id": 3}, {"id": 4}, {"id": 1}]
d = next(d for d in list_of_dicts if d["id"] == 1)
print(d)
Prints:
{'id': 1}
CodePudding user response:
Just use an ordinary for
loop. Then you can stop the loop when you find the one you want. The list comprehension will keep looping unnecessarily.
d_ = None
for d in list_of_dicts:
if d['id'] == 'the_id_i_want':
d_ = d
break
CodePudding user response:
Create a dict
with indices of the unique id
, then use that to select the dict
you want
d = [{"id": 1, "val": 2}, {"id": 2, "val": 2}]
inds = {x["id"]: i for i, x in enumerate(d)}
# if you want dict with id equal to 1
d[inds[1]]
# {'id': 1, 'val': 2}