大多数Pythonic方法可以从列表中获取一项?

发布于 2025-02-03 22:03:13 字数 249 浏览 2 评论 0原文

假设我有一个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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

有木有妳兜一样 2025-02-10 22:03:14

只需为循环使用普通即可。然后,当您找到想要的一个时,您可以停止循环。列表理解将不必要地循环。

d_ = None
for d in list_of_dicts:
    if d['id'] == 'the_id_i_want':
        d_ = d
        break

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
高冷爸爸 2025-02-10 22:03:14

您可以使用 next() ((注意:您可以使用default =参数指定未找到dict时返回的值):

list_of_dicts = [{"id": 3}, {"id": 4}, {"id": 1}]

d = next(d for d in list_of_dicts if d["id"] == 1)
print(d)

打印:

{'id': 1}

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}

铃予 2025-02-10 22:03:14

您可以避免使用生成器循环循环整个列表,以仅采用领先值:

d = next( 
    (d for d in list_of_dicts if d['id'] == 'the_id_i_want'), 
    None)

如果找不到,d将设置为none

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.

桃扇骨 2025-02-10 22:03:14

使用唯一id的索引创建dict,然后使用它选择dict您想要

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}

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}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文