且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查python的字典列表中是否存在密钥?

更新时间:2022-10-15 10:23:49

我可能会写:

>>>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]