如何检查python的字典列表中是否存在密钥? [英] How can I check if key exists in list of dicts in python?

查看:58
本文介绍了如何检查python的字典列表中是否存在密钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个看起来像这样的字典列表:

[{1: "a"}, {2: "b"}]

指示某个键是否在列表中的某个字典中的 Pythonic 方法是什么?

解决方案

我可能会写:

<预><代码>>>>lod = [{1: "a"}, {2: "b"}]>>>任何(1 in d for d in lod)真的>>>任何(3 in d for d in lod)错误的

尽管如果此列表中有很多字典,您可能需要重新考虑您的数据结构.

如果您想要找到第一个匹配项的索引和/或字典,一种方法是使用 nextenumerate:

<预><代码>>>>next(i for i,d in enumerate(lod) if 1 in d)0>>>next(d for i,d in enumerate(lod) if 1 in d){1:'一个'}>>>next((i,d) for i,d in enumerate(lod) if 1 in d)(0, {1: 'a'})

如果它不存在,这将引发 StopIteration:

<预><代码>>>>next(i for i,d in enumerate(lod) if 3 in d)回溯(最近一次调用最后一次):文件<ipython-input-107-1f0737b2eae0>",第 1 行,在 <module> 中next(i for i,d in enumerate(lod) if 3 in d)停止迭代

如果您想避免这种情况,您可以捕获异常或向 next 传递一个默认值,例如 None:

<预><代码>>>>next((i for i,d in enumerate(lod) if 3 in d), None)>>>

正如@drewk 的评论中所指出的,如果您想在多个值的情况下返回多个索引,您可以使用列表理解:

<预><代码>>>>lod = [{1: "a"}, {2: "b"}, {2: "c"}]>>>[i for i,d in enumerate(lod) if 2 in d][1, 2]

Say I have a list of dicts that looks like this:

[{1: "a"}, {2: "b"}]

What is the pythonic way to indicate if a certain key is in one of the dicts in the list?

解决方案

I'd probably write:

>>> lod = [{1: "a"}, {2: "b"}]
>>> any(1 in d for d in lod)
True
>>> any(3 in d for d in lod)
False

although if there are going to be a lot of dicts in this list you might want to reconsider your data structure.

If you want the index and/or the dictionary where the first match is found, one approach is to use next and enumerate:

>>> next(i for i,d in enumerate(lod) if 1 in d)
0
>>> next(d for i,d in enumerate(lod) if 1 in d)
{1: 'a'}
>>> next((i,d) for i,d in enumerate(lod) if 1 in d)
(0, {1: 'a'})

This will raise StopIteration if it's not there:

>>> next(i for i,d in enumerate(lod) if 3 in d)
Traceback (most recent call last):
  File "<ipython-input-107-1f0737b2eae0>", line 1, in <module>
    next(i for i,d in enumerate(lod) if 3 in d)
StopIteration

If you want to avoid that, you can either catch the exception or pass next a default value like None:

>>> next((i for i,d in enumerate(lod) if 3 in d), None)
>>>

As noted in the comments by @drewk, if you want to get multiple indices returned in the case of multiple values, you can use a list comprehension:

>>> lod = [{1: "a"}, {2: "b"}, {2: "c"}]
>>> [i for i,d in enumerate(lod) if 2 in d]
[1, 2]

这篇关于如何检查python的字典列表中是否存在密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆