2014-12-27 40 views
1

我做我的问题的简单的例子,在这里它是:蟒蛇:获得嵌套字典的价值在通用的方式

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

现在我想有这对本词典操作的方法,取值基于关键。

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

在不同的地方,这个泛型方法将被调用来获取值。

get_value(dic, 'a')将工作。

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

+0

你的意思'DIC [ 'B'] [ 'C']','不DIC [ '一'] [ 'B']',对吧? – 2014-12-27 15:01:40

回答

6

使用未绑定方法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 

UPDATE

如果使用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'