如何遍历json文件并使用值找到密钥名称



有人能帮我找到解决方案吗我有一个JSON文件,如下

{
"Parent1": ["Child1", "Child2","Child5"],
"Parent2": ["Child3", "Child4","Child5"]
}

期望值:使用子名称查找父名称的Python代码

用户输入:Child1
预期输出:Parent1

OR

用户输入:Child5
预期输出:Parent1,Parent2

这是一个可以使用的方法

choice = input("Enter search string ")
ans = []
for i,j in data.items():
if choice in j:
ans.append(i)

ans现在将包含您需要的密钥作为列表

您应该读取json文件,然后在字典上循环以找到与给定输入匹配的内容

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)

最新更新