can anyone please help me to find the solution I am having a JSON file like below
{
"Parent1": ["Child1", "Child2","Child5"],
"Parent2": ["Child3", "Child4","Child5"]
}
expectation: Python code to find the parent name using child name
User input: Child1
Expected output : Parent1
OR
User input: Child5
Expected output : Parent1,Parent2
CodePudding user response:
This is an apporach you can use
choice = input("Enter search string ")
ans = []
for i,j in data.items():
if choice in j:
ans.append(i)
ans will now contain the keys you need as a list
CodePudding user response:
You should read the json file and then loop over the dictionary to find matching for the given input
def find_key_name_by_value(json_input, key_to_find):
result = []
for key, value in input.items():
if key_to_find in value:
result.append(key)
return result
json_input = {
"Parent1": ["Child1", "Child2","Child5"],
"Parent2": ["Child3", "Child4","Child5"]
}
result = find_key_name_by_value(json_input, "Child4")
print(result)