【问题标题】:Pass nested dictionary location as parameter in Python在 Python 中将嵌套字典位置作为参数传递
【发布时间】:2017-03-21 00:26:01
【问题描述】:

如果我有一个嵌套字典,我可以通过这样的索引来获取一个键:

>>> d = {'a':{'b':'c'}}
>>> d['a']['b']
'c'

我可以将该索引作为函数参数传递吗?

def get_nested_value(d, path=['a']['b']):
    return d[path]

编辑:我知道我的语法不正确。它是正确语法的代理。

【问题讨论】:

  • 没有。你会得到TypeError: list indices must be integers, not str。
  • 你可以这样做,path = ['a','b'] 和 d[path[0]][path[1]]

标签: python parameter-passing


【解决方案1】:

您可以使用reduce(或python 3 中的functools.reduce),但这也需要您传入一个键的列表/元组:

>>> def get_nested_value(d, path=('a', 'b')):
        return reduce(dict.get, path, d)

>>> d = {'a': {'b': 'c'}}
>>> get_nested_value(d)
'c'
>>> 

(在您的情况下,['a']['b'] 不起作用,因为['a'] 是一个列表,而['a']['b'] 正在尝试在该列表的第“b”索引处查找元素)

【讨论】:

  • 谢谢,简洁的功能。我以前不知道!
  • 对于单深度字典,您需要传递一个空值,例如:('a', )
【解决方案2】:

不是真的,但是通过稍微重写你的函数体,你可以将键作为元组或其他序列传递:

def get_nested_value(d, keys):
    for k in keys:
        d = d[k]
    return d

d = {'a':{'b':'c'}}
print get_nested_value(d, ("a", "b"))

【讨论】:

    【解决方案3】:

    我遇到了同样的问题,我正在用递归函数解决它:

    def access_path (lambda json, path): 
        if len(path) == 0:
            return json
        else 
            return access_path(json[path[0]], path[1:]))
    

    这适用于嵌套字典和字典列表:

    test = {
        'a' : {
            'b' : 420
        },
        'c' : [
            {
                'id' : 'd1'
            },
            {
                'id' : 'd2'
            },
            {
                'id' : 'd3'
            },
        ]
    }
    
    print(access_path(test, ['a', 'b']))
    print(access_path(test, ['c', 1, 'id']))
    

    返回

    420
    d2
    

    【讨论】:

      【解决方案4】:

      看看https://github.com/akesterson/dpath-python。

      它使遍历嵌套字典变得容易得多。

      它将迭代出字典中的所有条件,因此不需要特殊的循环结构。

      【讨论】:

        猜你喜欢
        • 2021-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-14
        • 1970-01-01
        • 2021-09-26
        • 1970-01-01
        相关资源
        最近更新 更多