[英]How to know if a value exists in a list within a nested dictionary
How can i check if 'Anna' exists in the dictionary? 我如何检查字典中是否存在“安娜”? challenge seems to be accessing the value in the list: 挑战似乎正在访问列表中的值:
data = {"Pam": {"Job":"Pilot",
"YOB": "1986",
"Children": ["Greg", "Anna","Sima"]},
"Joe": {"Job":"Engineer",
"YOB": "1987"}}
If your dictionary is as above, and you simply want to test if "Anna" is in the "Children" list of the "Pam" sub-dictionary, you can simply do: 如果您的词典如上所述,并且您只想测试“ Anna”是否在“ Pam”子词典的“ Children”列表中,则只需执行以下操作:
print("Anna" in data["Pam"]["Children"])
but I assume you actually want something more general. 但我认为您实际上想要更一般的东西。 ;) ;)
Here's a recursive function that will check an object consisting of nested dictionaries and lists, looking for a given value. 这是一个递归函数,它将检查由嵌套字典和列表组成的对象,寻找给定值。 The outer object can be a dict or a list, so it's suitable for handling objects created from JSON. 外部对象可以是字典或列表,因此适合处理从JSON创建的对象。 Note that it ignores dict keys, it only looks at values. 请注意,它会忽略dict键,而只会查看值。 It will recurse as deeply as it needs to, to find a matching value, but it will stop searching as soon as it finds a match. 它会根据需要进行深度递归以找到匹配值,但是一旦找到匹配项,它将立即停止搜索。
def has_value(obj, val):
if isinstance(obj, dict):
values = obj.values()
elif isinstance(obj, list):
values = obj
if val in values:
return True
for v in values:
if isinstance(v, (dict, list)) and has_value(v, val):
return True
return False
# Test
data = {
"Pam": {
"Job": "Pilot",
"YOB": "1986",
"Children": ["Greg", "Anna", "Sima"]
},
"Joe": {
"Job": "Engineer",
"YOB": "1987"
}
}
vals = ("Pam", "Pilot", "1986", "1987", "1988", "YOB", "Greg",
"Anna", "Sima", "Engineer", "Doctor")
for v in vals:
print(v, has_value(data, v))
output 输出
Pam False
Pilot True
1986 True
1987 True
1988 False
YOB False
Greg True
Anna True
Sima True
Engineer True
Doctor False
The obj
you pass to has_value
must be a dict or a list, otherwise it will fail with 您传递给has_value
的obj
必须是字典或列表,否则将失败
UnboundLocalError: local variable 'values' referenced before assignment
You can use any
with a list comprehension to check if 'Anna'
exists as either a key in the dictionary or appears as an element in a subdictionary: 您可以将any
与列表推导一起使用,以检查'Anna'
是否作为字典中的键存在或作为子词典中的元素出现:
data = {"Pam": {"Job":"Pilot",
"YOB": "1986",
"Children": ["Greg", "Anna","Sima"]},
"Joe": {"Job":"Engineer",
"YOB": "1987"}}
if any(a == 'Anna' or 'Anna' in b.get('children', []) for a, b in data.items()):
pass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.