简体   繁体   English

如何检查字典中是否存在值,该值是否在另一个字典的列表中?

[英]How can I check if a value exists in a dictionary, that's in a list within another dictionary?

I have a dictionary that contains multiple keys and values, one of which contains a list of more dictionaries. 我有一本包含多个键和值的字典,其中一个包含更多词典的列表。 I need to be able to find if a given value exists within those dictionaries, but I'm unsure how to check against them when they exist not only within a list, but within an object property. 我需要能够找到这些字典中是否存在给定值,但是我不确定当它们不仅存在于列表中而且存在于对象属性中时,如何对它们进行检查。

While a for loop check could accomplish this, the property could end up holding hundreds of values, which would make this approach inefficient. 尽管for循环检查可以完成此操作,但该属性最终可能包含数百个值,这会使该方法效率低下。

I've also tried variations of: if <value> in <dict>[<list>][<dict2>] 我还尝试了以下方法的变体: if <value> in <dict>[<list>][<dict2>]

But, I keep getting TypeErrors that list indices must be an integer or slice (The values are strings). 但是,我不断收到TypeErrors列表索引必须是整数或切片(值是字符串)。

An example of the code would be: 该代码的示例为:

dictExample = {
"name": "yes",
"age": 25,
"Check_Me": [
    {"type": "code", "value": "001"},
    {"type": "code", "value": "002"},
    {"type": "code", "value": "003"},
    {"type": "code", "value": "004"},
    {"type": "code", "value": "005"}
    ],
}

if "007" not in dictExample["Check_Me"]["value"]:
    print("It works!")
else:
    print("Failure...")

(I cannot upload the actual code, but this is roughly what I am facing.) (我无法上传实际的代码,但这大致就是我所面临的。)

Expected output would be that the code runs without errors, and is successfully able to find if the value is in the nested dictionary or not. 预期的输出将是代码运行没有错误,并且能够成功地找到该值是否在嵌套字典中。

One example is to use the inbuilt any function which short circuits when the first match is found. 一个示例是使用内置的任何函数, 函数在找到第一个匹配项时会短路。 However there are several options 但是,有几种选择

if not any("007" in x["value"] for x in dictExample["Check_Me"]):
    print("It works!")
dictExample = {
"name": "yes",
"age": 25,
"Check_Me": [
    {"type": "code", "value": "001"},
    {"type": "code", "value": "002"},
    {"type": "code", "value": "003"},
    {"type": "code", "value": "004"},
    {"type": "code", "value": "005"}
    ],
}
if "007" not in [d['value'] for d in dictExample['Check_Me']]:
    print("It works!")
else:
    print("Failure...")
  • Just iterate over Check_Me and get all the values of key 'value' from dictionary. 只需遍历Check_Me并从字典中获取键'value'所有值即可。

You may need recursion: 您可能需要递归:

def val_in_dict(my_val, the_dict):
    for value in the_dict.values():
        if my_val == value:
            return True
        elif isinstance(value, list):
            for element in value:
                if isinstance(element, dict) and val_in_dict(my_val, element):
                    return True
    return False
if val_in_dict("007", d):
    print("It works")

You may also want to change a line up there to isinstance(value, (list, tuple)) or something more complicated. 您可能还想将一行更改为isinstance(value, (list, tuple))或更复杂的东西。 Using recursion allows you to be more flexible on how deep your data hierarchy can go. 使用递归可以使您更加灵活地掌握数据层次结构的深度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何检查嵌套在循环中的字典中是否存在值 - How can I check if a value exists in a dictionary that is nested within a loop 检查存储为字典值的列表中是否存在特定文本 - Check if specific text exists within a list stored as a dictionary's value 检查另一个字典中是否存在python字典中值列表中的值 - Check if a value from a list of values in a python dictionary exists in another dictionary 您如何检查字典中的字典中是否存在值? - How do you check to see if a value exists in a dictionary within a dictionary? 如何检查列表中的字典中是否存在某种值组合? - How can I check if a certain combination of values exists in a dictionary in a list? 如何检查字典中是否存在值 python - How can I check that a value exists in a dictionary or not in python 如何检查字典中是否存在值? - How to check if a value exists in a dictionary? 如何检查条件的值? 它们在字典列表中,字典在列表中 - how can I check the value for a condition? They are in the list of dictionaries and the dictionary is in the list 如何检查另一个字典列表中是否存在词典项的子集? - How to check whether a subset of dictionary items exists in another list of dictionaries? 如何知道嵌套字典的列表中是否存在值 - How to know if a value exists in a list within a nested dictionary
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM