如何平铺嵌套的python字典? [英] How to flatten nested python dictionaries?

查看:507
本文介绍了如何平铺嵌套的python字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图平铺嵌套字典:

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]

I'd like to display all values in lists: [4, 6, 3, 23, 3, 45, 2, 0, 6, 1, 2, 3,..., 2, 10, 8]

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

My first idea was to do in this way:

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

尽管我收到错误。

推荐答案

您可以使用简单的递归函数,如下所示。 >

You can use a simple recursive function as follows.

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

这篇关于如何平铺嵌套的python字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆