Python 在 JSON 字典中搜索特定值并返回该键

标签 python dictionary

我正在尝试搜索 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": ""
    }
}
}%

最佳答案

您需要构造一个字典来从描述映射到哈希码:

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

然后您可以通过以下方式访问它:

d['Cat Photo']

关于Python 在 JSON 字典中搜索特定值并返回该键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48954697/

相关文章:

python - 我正在尝试计算 txt 文件中的所有字母,然后按降序显示

python - 使用相同的键将两本词典合二为一?

python - 如何实现一个函数来覆盖单个值和多个值

python - 使用pygame添加图像

python - 在一个 Python 数据帧/字典中搜索另一个数据帧中的模糊匹配

python - Pubmed eutils esearch 的排序选项?

Python __hash__ : identity vs. 等价

python - 如何找到孤儿进程的pid

Java访问Queue<Map>中的Map

c# - 遍历包含对象的字典