[英]Python seach JSON dictionary for specific value and return that key
I'm trying to search each description entered in the JSON file to search for a match then return the hash key.我正在尝试搜索在 JSON 文件中输入的每个描述以搜索匹配项,然后返回哈希键。 Example: A search for 'Cat Photo' should return the hash key 'QmVQ8dU8cpNezxZHG2oc3xQi61P2n'.
示例:搜索“Cat Photo”应返回哈希键“QmVQ8dU8cpNezxZHG2oc3xQi61P2n”。 Any help would be great.
任何帮助都会很棒。
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"
Sample of JSON file: JSON 文件示例:
{
"hashlist": {
"QmVZATT8cQM3kwBrGXBjuKfifvrE": {
"description": "Test Video",
"url": ""
},
"QmVQ8dU8cpNezxZHG2oc3xQi61P2n": {
"description": "Cat Photo",
"url": ""
},
"QmYdWbMy8wPA7V12bX7hf2zxv64AG": {
"description": "Test Dir",
"url": ""
}
}
}%
You need to construct a dict to map from the description
to hashcode:您需要构造一个字典来从
description
映射到哈希码:
d = {v['description']: h for h, v in hashlist.items()}
Then you can access it simply by:然后您可以简单地通过以下方式访问它:
d['Cat Photo']
results = [k for k in d['hashlist'] if 'Cat' in d['hashlist'][k]['description']]
for result in results:
print(result)
Should sort you, let me know if you have problems.应该给你排序,如果你有问题,请告诉我。
Try this尝试这个
hash = next(k for k,v in hashlist.items() if v['description'] == 'Cat Photo')
Remember this will throw error if cat photo is not found in description key请记住,如果在描述键中找不到猫照片,这将引发错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.