python - 从嵌套字典中获取值

标签 python idioms

是否有从嵌套字典中获取值的标准方法?该函数相对容易编写,但我很好奇 PSL 或语言本身是否已有可以以这种方式使用的东西?

以下是我的意思的示例:

def grab_from_dict(d, *keys):
    assert isinstance(d, dict), 'd must be of type dict'

    current_dict = d
    for key in keys[0 : -1]:
        if key not in current_dict:
            return None

        current_dict = current_dict[key]

    if current_dict is None:
        return None

    return current_dict.get(keys[-1], None)

d = {
    'a' : {
        'b' : {
           'c1' : {
                'd' : 'leeloo'
            },
           'c2' : {
                'd' : None
            },
           'c3' : {
                'e' : None
            },
            'c4' : None
        }
    }
}

print grab_from_dict(d, 'a', 'b', 'c1')
> {'d': 'leeloo'}
print grab_from_dict(d, 'a', 'b', 'c1', 'd')
> leeloo
print grab_from_dict(d, 'a', 'b', 'c2')
> {'d': None}
print grab_from_dict(d, 'a', 'b', 'c2', 'd')
> None
print grab_from_dict(d, 'a', 'b', 'c3')
> {'e': None}
print grab_from_dict(d, 'a', 'b', 'c3', 'd')
> None
print grab_from_dict(d, 'a', 'b', 'c4')
> None
print grab_from_dict(d, 'a', 'b', 'c4', 'd')
> None
print grab_from_dict(d, 'a', 'b', 'c5')
> None
print grab_from_dict(d, 'a', 'b', 'c5', 'd')
> None

这给了我一种方法来获取嵌套字典深处的值,而不必担心父字典的存在。因此,不要这样写:

value = None
if 'a' in d and d['a'] not None:
    if 'b' in d['a'] and d['a']['b'] is not None:
        if 'c1' in d['a']['b'] and d['a']['b']['c1'] is not None:
            value = d['a']['b']['c1'].get('d', None)
print value
> leeloo

我可以这样写:

value = grab_from_dict(d, 'a', 'b', 'c1', 'd')
print value
> leeloo

如果缺少任何父级,该函数将简单地返回 None:

value = grab_from_dict(d, 'a', 'a', 'c1', 'd')
print value
> None

最佳答案

捕获异常应该有效:

try:
    result = d['a']['b']['c1']
except KeyError:
    result = None

关于python - 从嵌套字典中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19963914/

相关文章:

python - Django fixtures 和 AttributeError : 'QuerySet' object has no attribute <custom_model_method>

c++ - 我什么时候应该使用新的 ranged-for,我可以将它与新的 cbegin/cend 结合使用吗?

c++ - 即时推导

c++ - 什么是模板<typename T, T t> 习语?

python - InvalidArgumentError : Received a label value of 8825 which is outside the valid range of [0, 8825) SEQ2SEQ 模型

python - 如何修复 pip : cannot import name main?(pip 已安装并且 pip3 工作正常)

python - Django:按用户过滤草稿会导致错误

go - golang 中是否有惯用的作用域语义?

smalltalk - 集合中元素的共现

Python JSON转储/append 到.txt,每个变量都在新行