使用“路径”访问不同级别的嵌套字典

时间:2013-04-29 12:47:44

标签: python dictionary

我想定义一个小包装函数,它使用某种“路径”来访问不同级别的嵌套字典:

D = {'key1': valueA,
     'key2': {'key21': valueB,
             {'key22': valueC}

在这个简单的例子中,我想编写一个函数作为参数,例如,像

这样的元组
dict_path = ('key2', 'key22')

>>>nested_getter(dict_path)
valueC

2 个答案:

答案 0 :(得分:4)

D = {'key1': valueA,
     'key2': {'key21': valueB,
              'key22': valueC}}


def nested_getter(root, path):
    for elem in path:
        root = root[elem]
    return root

你可以这样做:

>>> nested_getter(D, ('key2', 'key22'))
3

答案 1 :(得分:4)

def nested_getter(d, keys):
    return reduce(dict.get, keys, d)