按路径获取字典键(字符串)

时间:2017-12-25 14:56:31

标签: python dictionary

我有这条路可以不时改变:

'#/path/to/key'

路径的各个部分没有定义,所以这个值也很好

'#/this/is/a/longer/path'

我将此密钥拆分为' /'所以我得到了

['#', 'path', 'to', 'key']

我需要在这条路上找到钥匙,让我们说我的dict是exp,所以我需要到达这里:

exp['path']['to']['key']

我怎么可能知道如何获得这个密钥?

7 个答案:

答案 0 :(得分:5)

使用递归,Luke ......

def deref_multi(data, keys):
    return deref_multi(data[keys[0]], keys[1:]) \
        if keys else data

last = deref_multi(exp, ['path','to','key'])

答案 1 :(得分:2)

使用 functools 代替递归:

# Define:
from functools import partial, reduce
deref = partial(reduce, lambda d, k: d[k])

# Use:
exp = {'path': {'to': {'key': 42}}}
deref(('path', 'to', 'key'), exp)

3 岁的问题,我知道...我真的很喜欢 functools。

答案 2 :(得分:1)

>>> exp = {'path': {'to': {'key': 42}}}
>>> my_key = exp
>>> for i in '#/path/to/key'.split('/')[1:]:
>>>     my_key = my_key[i]
>>> print(my_key)
42

但我对你如何检索这样的字典有点好奇

答案 3 :(得分:1)

假设你的意思是你的数组['#', 'path', 'to', 'key']的索引从索引1开始嵌入到嵌套中,你可以从第二个开始遍历列表中的每个项目并深入挖掘通过每次迭代。

例如,在Python 3中你可以这样做。

def get_key_from_path(exp, path):
    """Returns the value at the key from <path> in <exp>.
    """
    cur = exp
    for dir in path[1:]:
        cur = exp[dir]
    return cur

答案 4 :(得分:1)

def get_key_by_path(dict_obj, path_string):
    path_list = path_string.split('/')[1:]
    obj_ptr = dict_obj
    for elem in path_list:
        obj_ptr = obj_ptr[elem]
    return obj_ptr

答案 5 :(得分:1)

这里有一些很好的答案,但是它们都没有考虑到不正确的路径,或者在某些方面导致某些不可订阅的路径。下面的代码可能会让您在处理此类案例时有更多的余地,而到目前为止其他代码只会引发错误或出现意外行为。

path = '#/path/to/key'
exp = {'path' : { 'to' : { 'key' : "Hello World"}}}

def getFromPath(dictionary, path):
    curr = dictionary
    path = path.split("/")[1:] # Gets rid of '#' as it's uneccessary 
    while(len(path)):
        key = path.pop(0)
        curr = curr.get(key)
        if (type(curr) is not dict and len(path)):
            print("Path does not exist!")
            return None 
    return curr

print(getFromPath(exp, path)) #Your value

答案 6 :(得分:1)

我建议您使用python-benedict,它是具有完整键路径支持和许多实用程序方法的python dict子类。

您只需要投射现有的字典:

exp = benedict(exp)
# now your keys can be dotted keypaths too
exp['path.to.key']

以下是库和文档: https://github.com/fabiocaccamo/python-benedict