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

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

问题描述

例如我有一个嵌套字典。只有一种方法才能使价值安全吗?

  try:
example_dict ['key1'] ['key2' ]
除了KeyError:
pass

或者也许python有一个方法,如 get()为嵌套字典?

解决方案

您可以使用 get 两次:

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

这将返回如果 key1 key2 不存在。



请注意,如果 example_dict ['key1'] 存在但是不是dict(或者),则仍然可以引发 AttributeError 一个具有获取方法的类似dict的对象)。如果 example_dict ['key1],您发布的 try..except 代码会引发 TypeError '] 是不可编辑的。



另一个区别是 try ... except 第一个缺少密钥后立即发生短路。 的链接呼叫不。






如果你愿意要保留语法 example_dict ['key1'] ['key2'] ,但不希望它提高KeyErrors,那么您可以使用 Hasher配方

  class Hasher(dict) :
#http://stackoverflow.com/a/3405143/190597
def __missing __(self,key):
value = self [key] = type(self)()
返回值

example_dict = Hasher()
print(example_dict ['key1'])
#{}
print(example_dict ['key1'] [ 'key2'])
#{}
print(type(example_dict ['key1'] ['key2']))
#< class'__main __。Hasher'>

请注意,当一个键丢失时,这将返回一个空的Hasher。



由于 Hasher dict 的子类,您可以以相同的方式使用Hasher您可以使用 dict 。所有相同的方法和语法都可以使用,Hashers只是对不同的键进行处理。



您可以转换常规的 dict 成为 Hasher 如下:

  hasher = Hasher(example_dict)

并将 Hasher 转换为常规 dict 同样容易:

  regular_dict = dict(hasher)






另一个替代方法是在辅助函数中隐藏丑陋: p>

  def safeget(dct,* keys):
键中的键:
try:
dct = dct [key]
除了KeyError:
返回无
返回dct

所以其余的代码可以保持比较可读:

  secureget(example_dict,'key1','key2' )


For example i have a nested dictionary. Is there only one way to get values safe?

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

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

解决方案

You could use get twice:

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

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

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.

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


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):
    # http://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'>

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

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.

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

hasher = Hasher(example_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')

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

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