获取嵌套字典值的安全方法 [英] Safe method to get value of nested dictionary

查看:50
本文介绍了获取嵌套字典值的安全方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌套的字典.只有一种安全地获取价值的方法吗?

I have a nested dictionary. Is there only one way to get values out safely?

try:
    example_dict['key1']['key2']
except KeyError:
    pass

或者python对于嵌套字典有类似 get()的方法吗?

Or maybe python has a method like get() for nested dictionary ?

推荐答案

您可以使用 get 两次:

example_dict.get('key1', {}).get('key2')

如果 key1 key2 不存在,它将返回 None .

This will return None if either key1 or key2 does not exist.

请注意,如果存在 example_dict ['key1'] 但不是dict(或带有的类似dict的对象),这仍可能引发 AttributeError get 方法).如果 example_dict ['key1'] 无法取消订阅,则您发布的 try..except 代码将引发 TypeError .

Note that this could still raise an AttributeError if example_dict['key1'] exists but is not a dict (or a dict-like object with a get method). The try..except code you posted would raise a TypeError instead if example_dict['key1'] is unsubscriptable.

另一个区别是,在第一个丢失的键之后, try ... except 会立即短路. get 调用链没有.

Another difference is that the try...except short-circuits immediately after the first missing key. The chain of get calls does not.

如果您希望保留语法 example_dict ['key1'] ['key2'] ,但不希望它引发KeyError,则可以使用

If you wish to preserve the syntax, example_dict['key1']['key2'] but do not want it to ever raise KeyErrors, then you could use the Hasher recipe:

class Hasher(dict):
    # https://stackoverflow.com/a/3405143/190597
    def __missing__(self, key):
        value = self[key] = type(self)()
        return value

example_dict = Hasher()
print(example_dict['key1'])
# {}
print(example_dict['key1']['key2'])
# {}
print(type(example_dict['key1']['key2']))
# <class '__main__.Hasher'>

请注意,如果缺少密钥,这将返回一个空的Hasher.

Note that this returns an empty Hasher when a key is missing.

由于 Hasher dict 的子类,因此可以像使用 dict 一样使用Hasher.可以使用所有相同的方法和语法,而Hashers只是以不同的方式对待丢失的密钥.

Since Hasher is a subclass of dict you can use a Hasher in much the same way you could use a dict. All the same methods and syntax is available, Hashers just treat missing keys differently.

您可以像这样将常规 dict 转换为 Hasher :

You can convert a regular dict into a Hasher like this:

hasher = Hasher(example_dict)

并轻松地将 Hasher 转换为常规的 dict :

and convert a Hasher to a regular dict just as easily:

regular_dict = dict(hasher)


另一种替代方法是将丑陋隐藏在辅助函数中:


Another alternative is to hide the ugliness in a helper function:

def safeget(dct, *keys):
    for key in keys:
        try:
            dct = dct[key]
        except KeyError:
            return None
    return dct

因此,其余代码可以保持相对可读性:

So the rest of your code can stay relatively readable:

safeget(example_dict, 'key1', 'key2')

这篇关于获取嵌套字典值的安全方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆