如何拼合嵌套的python字典?

Mon*_*ica 2 python dictionary

我正在尝试拼合嵌套的字典:

dict1 = {
    'Bob': {
        'shepherd': [4, 6, 3],
        'collie': [23, 3, 45],
        'poodle': [2, 0, 6],
    },
    'Sarah': {
        'shepherd': [1, 2, 3],
        'collie': [3, 31, 4],
        'poodle': [21, 5, 6],
    },
    'Ann': {
        'shepherd': [4, 6, 3],
        'collie': [23, 3, 45],
        'poodle': [2, 10, 8],
    }
}
Run Code Online (Sandbox Code Playgroud)

我想显示列表中的所有值:[4、6、3、23、3、45、2、0、6、1、2、3,...,2、10、8]

我的第一个想法就是这样:

dict_flatted = [ i for name in names.values() for dog in dogs.values() for i in dog]
Run Code Online (Sandbox Code Playgroud)

虽然我得到了错误。我很乐意提供处理技巧。

Dae*_*Lee 5

您可以如下使用简单的递归函数。

def flatten(d):    
    res = []  # Result list
    if isinstance(d, dict):
        for key, val in d.items():
            res.extend(flatten(val))
    elif isinstance(d, list):
        res = d        
    else:
        raise TypeError("Undefined type for flatten: %s"%type(d))

    return res


dict1 = {
    'Bob': {
        'shepherd': [4, 6, 3],
        'collie': [23, 3, 45],
        'poodle': [2, 0, 6],
    },
    'Sarah': {
        'shepherd': [1, 2, 3],
        'collie': [3, 31, 4],
        'poodle': [21, 5, 6],
    },
    'Ann': {
        'shepherd': [4, 6, 3],
        'collie': [23, 3, 45],
        'poodle': [2, 10, 8],
    }
}

print( flatten(dict1) )
Run Code Online (Sandbox Code Playgroud)