Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python:以通用方式获取嵌套字典的值_Python_Dictionary - Fatal编程技术网

python:以通用方式获取嵌套字典的值

python:以通用方式获取嵌套字典的值,python,dictionary,Python,Dictionary,我正在为我的问题做一个简单的用例,它是: dic = {'a': 1, 'b': {'c': 2}} 现在我想要一个在这个字典上操作的方法,基于键获取值 def get_value(dic, key): return dic[key] 在不同的位置,将调用此通用方法来获取值 get_值(dic,'a')将起作用 是否有可能以更通用的方式获取值2(dic['b']['c'])。使用未绑定方法(或dict.\uuuu getitem\uuuuu)和: 更新 如果您使用dict.get

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

dic =  {'a': 1, 'b': {'c': 2}}
现在我想要一个在这个字典上操作的方法,基于键获取值

def get_value(dic, key):
     return dic[key]
在不同的位置,将调用此通用方法来获取值

get_值(dic,'a')
将起作用

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

使用未绑定方法(或
dict.\uuuu getitem\uuuuu
)和:

更新

如果您使用
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'
使用未绑定的方法(或
命令.uuu getitem_uuu
)和:

更新

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

你的意思是
dic['b']['c']
,不是
dic['a']['b']
,对吧?你的意思是
dic['b']['c']
,不是
dic['a']['b']
,对吗?
>>> reduce(dict.__getitem__, ['x', 'c'], OrderedDict({'a': 1, 'b': {'c': 2}}))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'x'