Reputation: 79
I'm trying to search each description entered in the JSON file to search for a match then return the hash key. Example: A search for 'Cat Photo' should return the hash key '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:
{
"hashlist": {
"QmVZATT8cQM3kwBrGXBjuKfifvrE": {
"description": "Test Video",
"url": ""
},
"QmVQ8dU8cpNezxZHG2oc3xQi61P2n": {
"description": "Cat Photo",
"url": ""
},
"QmYdWbMy8wPA7V12bX7hf2zxv64AG": {
"description": "Test Dir",
"url": ""
}
}
}%
Upvotes: 1
Views: 359
Reputation: 34667
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.
Upvotes: 0
Reputation: 9931
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
Upvotes: 0
Reputation: 16404
You need to construct a dict to map from the description
to hashcode:
d = {v['description']: h for h, v in hashlist.items()}
Then you can access it simply by:
d['Cat Photo']
Upvotes: 1