Skip to main content
 首页 » 编程设计

python之在python中访问多维字典时,如何返回默认值而不是键错误

2025年05月04日14leader

我正在尝试从多维字典中获取一个值,例如,它看起来像这样:

count = {'animals': {'dogs': {'chihuahua': 23}} 

所以如果我想知道我有多少吉娃娃,我正在打印 count['animals']['dogs']['chihuahua']

但我也想访问 count['vehicles']['cars']['vw golf'],我想返回 0 而不是关键错误。

实际上我正在这样做:

if not 'vehicles' in count: 
    count['vehicles'] = {} 
if not 'cars' in count['vehicles']: 
    count['vehicles']['cars'] = {} 
if not 'vw golf' in count['vehicles']['cars']['vw golf']: 
    count['vehicles']['cars']['vw golf'] = 0 

我怎样才能做得更好?

我正在考虑从 dict 继承的某种类型的类,但这只是一个想法。

请您参考如下方法:

你可以这样做:

return count.get('vehicles', {}).get('cars', {}).get('vw golf', 0) 

基本上,如果没有找到就返回一个空字典,最后得到计数。

假设数据集仅采用指定格式,这将起作用。它不会引发错误,但是您可能需要针对其他数据类型对其进行调整

演示

>>> count = {'animals': {'dogs': {'chihuahua': 23}}} 
>>> count.get('vehicles', {}).get('cars', {}).get('vw golf', 0) 
0 
>>> count = {'vehicles': {'cars': {'vw golf': 100}}} 
>>> count.get('vehicles', {}).get('cars', {}).get('vw golf', 0) 
100 
>>>