如何展平嵌套的python词典?

时间:2016-08-25 01:41:16

标签: 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],
    }
}

我想在列表中显示所有值: [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]

虽然我收到了错误。我很乐意提供如何处理它的提示。

4 个答案:

答案 0 :(得分:4)

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

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) )

答案 1 :(得分:2)

您正在尝试使用不存在的变量。

使用此

dict_flatted = [ i for names in dict1.values() for dog in names.values() for i in dog]

答案 2 :(得分:2)

递归函数可以是单行:

# npm install 
bash: npm: command not found

# which npm
which: no npm in (/mingw64/bin:/usr/local/bin:/usr/bin:/bin:/c/Windows/System32:/c/Windows:/c/Windows/System32/Wbem:/c/Windows/System32/WindowsPowerShell/v1.0/)

Nota:是duplicate question

的答案

答案 3 :(得分:0)

我从@DaewonLee的代码开始,将其扩展到更多数据类型并在列表中递归:

theHero = Superhero("Eternal", "75", "50", "100", "-45 Points")
#---------^^^^^^^^^-----------
# instead of
#-----------------------------
# theHero = theHero("Eternal", "75", "50", "100", "-45 Points")
#-----------×××××××-----------
相关问题