Troy Wilson
Troy Wilson

Reputation: 79

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. 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

Answers (3)

hd1
hd1

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

Arpit Solanki
Arpit Solanki

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

llllllllll
llllllllll

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

Related Questions