【问题标题】:Search nested dicts for key trees在嵌套字典中搜索关键树
【发布时间】:2016-12-16 06:07:42
【问题描述】:

我想检查嵌套字典中是否存在键元组,类似于dict.get。功能可以实现如下。

nested_dict = {
    'x': 1,
    'a': {
        'b': {
            'c': 2,
            'y': 3
        },
        'z': 4
    }
}

def check(nested, *path):
    for key in path:
        if isinstance(nested, dict) and key in nested:
            nested = nested[key]
        else:
            return False
    return True


check(nested_dict, 'a', 'b', 'c')  # True
check(nested_dict, 'x')  # True
check(nested_dict, 'a', 'b', 'y')  # True
check(nested_dict, 'a', 'z')  # True

check(nested_dict, 'y')  # False
check(nested_dict, 'a', 'y')  # False
check(nested_dict, 'a', 'b', 'c', 'y')  # False

是否有更简洁(或更好的内置)方法来执行此操作?

【问题讨论】:

    标签: python python-3.x dictionary nested python-3.5


    【解决方案1】:

    对于 python 3.x 执行from functools import reduce

    您可以包装try .. except KeyError(和TypeError)并返回适当的布尔值:

    >>> reduce(lambda x,y: x[y], ["a", "b", "c"], nested_dict)
    2
    >>> reduce(lambda x,y: x[y], ["a", "b", "d"], nested_dict)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 1, in <lambda>
    KeyError: 'd'
    

    PS:这句话有时写起来很有趣。但老实说,我会将您的版本用于任何生产代码。

    【讨论】:

      猜你喜欢
      • 2011-12-02
      • 2015-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-01
      • 1970-01-01
      • 2016-08-16
      • 1970-01-01
      相关资源
      最近更新 更多