繁体   English   中英

用键列表遍历多维字典的一种优雅方法?

[英]An elegant way of walking a multidimensional dict with a list of keys?

我想使用键列表遍历多维字典。 在最后一个键处,我将返回该值。

我将得到该列表,它将映射到字典的键,但是我不知道我需要深入多少。 换句话说,我不会事先知道键列表中有多少个项目。

这是我想出的。 有没有更优雅的方式做到这一点?

在我的示例中,walk_to_value()将返回“三个值”:

d = {'one': {'two': {'three': 'the three value'}}}
l = ['one','two','three']

def walk_to_value(d, l):
    e = l.pop(0)
    d1 = d[e]
    if (type(d1) == dict):
            return walk_to_value(d1, l)
    else:
            return d1

print walk_to_value(d, l)
def walk_to_value(d, l):
    for e in l:
        d = d[e]
    return d

如果列表中的键比字典中的级别多,我认为早点返回是没有用的,但这取决于您。

使用reduce()

from operator import getitem

def walk_to_value(d, l):
     return reduce(getitem, l, d)

或一个简单的循环:

def walk_to_value(d, l):
    result = d
    for field in l:
        result = result[field]
    return result
def traverse_tree(x, looking):
    def f(dic):
        if looking not in dic.keys():
            return reduce(lambda x, y: f(dict(y)) or x, filter(lambda y: isinstance(y, dict), dic.values()), False)
        return dic[looking]
    return f(x)

这样,只需将“三个”作为外观,它就会为您找到。 如果当前列表中有3个(顶部顶部),则将其返回,而无需在树中进一步检查。 如果不是,它将收集该级别的所有字典,然后重试。 找到密钥后,它将简单地返回它。 否则函数返回False。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM