用于在嵌套字典中搜索值的库,返回值键路径

时间:2017-11-09 16:30:33

标签: python python-2.7 python-3.x dictionary

考虑你有这样的字典:

{
    "keys": {
        "key1": {
            "param1": "value1",
            "param2": "value2"
        },
        "key2": {
            "param1": "param_value1",
            "param2": "param_value2"
        }
    }
}

您是否有任何关于如何搜索可能嵌套在某个内部dict级别的值并且返回该值的完整路径的想法。

I.E search("param_value2")会返回类似keys/key2/param2的内容 我想有一些库可以提供这种功能。

1 个答案:

答案 0 :(得分:-1)

这适用于你问题中的词典

dct = {
    "keys": {
        "key1": {
            "param1": "value1",
            "param2": "value2"
        },
        "key2": {
            "param1": "param_value1",
            "param2": "param_value2"
        }
    }
}


def search_value(searched_value):
    path = 'keys/'
    for key1,value1 in dct['keys'].items():
        for key2,value2 in dct['keys'][key1].items():
            if value2 == searched_value:
                path = 'keys/{0}/{1}'.format(key1,key2)
                break
    return path

print(search_value('param_value2'))
#>>>keys/key2/param2