I would like to extract the keys path whose value is Wally from the program
arr = []
sub_arr = []
def extract(obj, sub_arr, val):
if isinstance(obj, dict):
for k, v in obj.items():
if isinstance(v, (dict, list)):
sub_arr.append(k)
extract(v, sub_arr, val)
elif v == val:
sub_arr.append(k)
arr.append(sub_arr)
sub_arr = []
elif isinstance(obj, list):
for item in obj:
if isinstance(item, (dict, list)):
sub_arr.append(obj.index(item))
extract(item, sub_arr, val)
elif item == val:
sub_arr.append(obj.index(item))
arr.append(sub_arr)
sub_arr = []
return arr
obj = {
"News": [
{
"Title": "NewsA",
"Tags": ["Gossiping"],
"Date": "2021/06/26",
"Detail": {
"Author": "Wally",
"Content": "Hello World"
}
},
{
"Title": "NewsB",
"Tags": ["Social", "Wally"],
"Date": "2021/06/27",
"Detail": {
"Author": "Andy",
"Content": "Taiwan NO.1"
}
}
]
}
print(extract(obj, sub_arr, "Wally"))
This is the best result I've got so far
[
['News', 0, 'Tags', 'Detail', 'Author', 1, 'Tags', 1, 'Detail']
, ['News', 0, 'Tags', 'Detail', 'Author', 1, 'Tags', 1, 'Detail']
]
My desired value would be like this
[['News', 0, 'Detail', 'Author'], ['News', 1, 'Tags', 1]]
Pretty stuck right here. Is there something that I've missed? Would appreciate a little help