如何拼合嵌套的python词典?

如何拼合嵌套的python词典?,第1张

如何拼合嵌套的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 resdict1 = {    '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) )


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5630243.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存