Python搜索特定值的JSON字典并返回该键

Python搜索特定值的JSON字典并返回该键,python,dictionary,Python,Dictionary,我试图搜索JSON文件中输入的每个描述,以搜索匹配项,然后返回哈希键。示例:“Cat Photo”搜索应返回散列键“QmVQ8dU8cpNezxZHG2oc3xQi61P2n”。任何帮助都会很好 searchTerm = raw_input('Enter search term: ') with open('hash.json', 'r') as file: data = json.load(file) hashlist = data['hashlist'] if search

我试图搜索JSON文件中输入的每个描述,以搜索匹配项,然后返回哈希键。示例:“Cat Photo”搜索应返回散列键“QmVQ8dU8cpNezxZHG2oc3xQi61P2n”。任何帮助都会很好

searchTerm = raw_input('Enter search term: ')
with open('hash.json', 'r') as file:
    data = json.load(file)
    hashlist = data['hashlist']

if searchTerm in hashlist == True:
        print key
    else:
        print "not found"
JSON文件示例:

   {
"hashlist": {
    "QmVZATT8cQM3kwBrGXBjuKfifvrE": {
        "description": "Test Video",
        "url": ""
    },
    "QmVQ8dU8cpNezxZHG2oc3xQi61P2n": {
        "description": "Cat Photo",
        "url": ""
    },
    "QmYdWbMy8wPA7V12bX7hf2zxv64AG": {
        "description": "Test Dir",
        "url": ""
    }
}
}%

如果您有问题,请告诉我。

您需要构造一个dict,以将
说明映射到hashcode:

d = {v['description']: h for h, v in hashlist.items()}
然后,您可以通过以下方式访问它:

d['Cat Photo']
试试这个

hash = next(k for k,v in hashlist.items() if v['description'] == 'Cat Photo')

请记住,如果在描述码中找不到cat photo,这将引发错误

我将DictionInstance更改为hashlist,并获得此错误值error:要解包的值太多。请现在尝试一下?没有JSON字典;有JSON对象,
JSON.load
使用它们来创建
dict
类的实例。这非常有效!我刚刚添加了print d[searchTerm],效果很好。如果找不到“未找到”,我将如何添加“未找到”@liliscent@TroyWilson
d.get('xxx','notfound')
get()
将提供一个默认值(如果键不存在)。
hash = next(k for k,v in hashlist.items() if v['description'] == 'Cat Photo')