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:
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. Note that it ignores dict keys, it only looks at values. 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
UnboundLocalError: local variable 'values' referenced before assignment