我正在尝试搜索JSON文件中输入的每个描述以搜索匹配项,然后返回哈希键。示例:搜索“猫照片”应返回哈希键“ 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": ""
    }
}
}%

最佳答案

您需要构造一个字典以将description映射到哈希码:

d = {v['description']: h for h, v in hashlist.items()}


然后,您可以通过以下方式简单地访问它:

d['Cat Photo']

10-08 11:11