[英]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. 预期的输出将是代码运行没有错误,并且能够成功地找到该值是否在嵌套字典中。
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...")
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.