我正在尝试搜索在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": ""
}
}
}%
答案 0 :(得分:1)
您需要构建一个dict,以便从description
映射到hashcode:
d = {v['description']: h for h, v in hashlist.items()}
然后您可以通过以下方式访问它:
d['Cat Photo']
答案 1 :(得分:0)
results = [k for k in d['hashlist'] if 'Cat' in d['hashlist'][k]['description']]
for result in results:
print(result)
如果你有问题,请告诉我。
答案 2 :(得分:0)
试试这个
hash = next(k for k,v in hashlist.items() if v['description'] == 'Cat Photo')
如果在描述键
中找不到猫照,请记住这会抛出错误