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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14790980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:26:35  来源:igfitidea点击:

How can I check if key exists in list of dicts in python?

pythonpython-2.7

提问by user2057574

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?

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

采纳答案by DSM

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 nextand enumerate:

如果您想要找到第一个匹配项的索引和/或字典,一种方法是使用nextand 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 StopIterationif it's not there:

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

>>> 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 nexta default value like None:

如果你想避免这种情况,你可以捕获异常或传递next一个默认值,如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:

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

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

回答by Rohit Jain

Use anyfunction with a generator:

any函数与生成器一起使用:

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

anyfunction returns True, if at least one element in the iterablepassed to it is True. But you really need to consider, why are you not having all the key: valuepairs in a single dict?

any函数返回True,如果iterable传递给它的元素中至少有一个是True。但是你真的需要考虑,为什么你不把所有的key: value对都放在一个dict

回答by Ranvijay Sachan

parsedData=[]
dataRow={}
if not any(d['url'] == dataRow['url'] for d in self.parsedData):
       self.parsedData.append(dataRow)

回答by Lyncean Patel

To see in single dictoray we use 'in' keyword:

要查看单个字典,我们使用 'in' 关键字:

key in dic_instance

To check in list of dictionary, iterate through dictionary list and use 'any' function, so if key found in any of the dictionary, it will not iterate the list further.

要检查字典列表,请遍历字典列表并使用“any”函数,因此如果在任何字典中找到键,则不会进一步迭代列表。

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

回答by Marky0

To search through deeply nested data structure I used this code to recursively look for keys in both lists and dictionaries

为了搜索深层嵌套的数据结构,我使用此代码递归查找列表和字典中的键

def isKey(dictORlist, key):
# dictORlist is the data structure you want to search
# key is the keyword you want to search for
def checkList(List, key):
    if isinstance(List, list):
        for i in List:
             return isKey(i, key)

result = checkList(dictORlist, key)
if isinstance(dictORlist, dict):
    for k in dictORlist.keys():
        data = dictORlist[k]
        if k == key:
            return True
        elif isinstance(data, dict):
            result = isKey(data, key)
        else:
            result = checkList(data, key)

if result == None:
    result = False
return result

回答by FastGTR

I was thrown aback by what was possible in python2 vs python3. I will answer it based on what I ended up doing for python3. My objective was simple: check if a json response in dictionary format gave an error or not. My dictionary is called "token" and my key that I am looking for is "error"

我对 python2 与 python3 中可能发生的事情感到震惊。我将根据我最终为 python3 做的事情来回答它。我的目标很简单:检查字典格式的 json 响应是否有错误。我的字典叫做“token”,我要找的键是“error”

if ((token.get('error', None)) is None):
    do something

I am looking for key "error" and if it was not there, then setting it to value of None, then checking is the value is None, if so proceed with my code. An else statement to handle the if I do have the key "error

我正在寻找关键的“错误”,如果它不存在,则将其设置为 None 的值,然后检查该值是否为 None,如果是,则继续我的代码。一个 else 语句来处理 if I do have the key "error