您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何拼合嵌套的python词典?

如何拼合嵌套的python词典?

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

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 2022/1/1 18:37:14 有296人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶