【问题标题】:python: get value of nested dictionary in generic way [duplicate]python:以通用方式获取嵌套字典的值[重复]
【发布时间】:2014-12-27 14:59:04
【问题描述】:

我正在为我的问题做一个简单的用例,这里是:

dic =  {'a': 1, 'b': {'c': 2}}

现在我想要一个在这个字典上操作的方法,根据键获取值。

def get_value(dic, key):
     return dic[key]

在不同的地方会调用这个通用方法来获取值。

get_value(dic, 'a') 会起作用。

是否有可能以更通用的方式获取值2 (dic['b']['c'])

【问题讨论】:

  • 你的意思是dic['b']['c'],不是dic['a']['b'],对吧?

标签: python dictionary


【解决方案1】:

使用未绑定方法dict.get(或dict.__getitem__)和reduce

>>> # from functools import reduce  # Python 3.x only
>>> reduce(dict.get, ['b', 'c'], {'a': 1, 'b': {'c': 2}})
2

>>> reduce(lambda d, key: d[key], ['b', 'c'], {'a': 1, 'b': {'c': 2}})
2

更新

如果您使用dict.get 并尝试访问不存在的密钥,它可以通过返回None 来隐藏KeyError

>>> reduce(dict.get, ['x', 'c'], OrderedDict({'a': 1, 'b': {'c': 2}}))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: descriptor 'get' requires a 'dict' object but received a 'NoneType'

为防止这种情况,请使用dict.__getitem__:

>>> reduce(dict.__getitem__, ['x', 'c'], OrderedDict({'a': 1, 'b': {'c': 2}}))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'x'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-04
    • 2021-05-10
    • 2019-12-04
    • 2021-08-27
    • 1970-01-01
    • 2022-10-07
    • 2019-06-04
    相关资源
    最近更新 更多