大多数Pythonic方法可以从列表中获取一项?
假设我有一个dict的列表dict ['id']
是唯一的,我想访问一个特定的dict。
这就是我通常或多或少地这样做的方式。
d_ = [d for d in list_of_dicts where d['id']=='the_id_i_want'][0]
有更好/清洁/更多的Pythonic方法可以做到这一点吗?
这是一个API响应,否则我首先将其作为命令。
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?
This is an API response, otherwise I'd just make it a dict in the first place.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只需为循环使用普通
即可。然后,当您找到想要的一个时,您可以停止循环。列表理解将不必要地循环。
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.您可以使用
next()
((注意:您可以使用default =
参数指定未找到dict时返回的值):打印:
You can use
next()
(Note: you can usedefault=
parameter to specify value to return when dict is not found):Prints:
您可以避免使用生成器循环循环整个列表,以仅采用领先值:
如果找不到,
d
将设置为none
。You can avoid looping over the entire list using a generator to take just the leading value:
Here, if it is not found,
d
will be set toNone
.使用唯一
id
的索引创建dict
,然后使用它选择dict
您想要Create a
dict
with indices of the uniqueid
, then use that to select thedict
you want