如何使用单个键访问嵌套字典中的值?

How can I access value in nested dictionary using a single key?

假设我有一个嵌套字典,它是从 pickle 文件中提取的,它包含各种级别,我想通过只给出最后一个键来获取值。考虑到自己的 'branch'.

,密钥是唯一的

主要问题是我有多个键和级别:

 dict = {
    
    'A': {
        
        'X': {
            1: [...],
            2: [...]
        },
        
        'Y': {
            3: [...],
            4: [...]
        }
    }
    
    'B': {
        
        'G': {
            
            'H': {
                
                'Z': [...]
            }
        }
    }
    
    'C': [...]
 
 }

我该怎么做?

一个简单的解决方案是一个甚至适用于嵌套、嵌套字典的递归函数

outer_dict = {'outer': {'inner': 10, 'even_inner': {'innerst': 25}}}

和函数:

def get_val(search_dict, key):
    """ recursive searching the dict """
    for elem in search_dict:
        if elem == key:
            return search_dict[elem]
        if isinstance(search_dict[elem], dict):
            retval = get_val(search_dict[elem], key)
            if retval is not None:
                return retval
value = get_val(outer_dict, 'innerst')
print(value)
>> 25

问题: 如果密钥不是唯一的,您将只会获得第一场比赛。如果键可以出现多次,您将需要一个列表来填充值。

下次请举例说明!