Python 如何用嵌套的dict展平dict列表

Python 如何用嵌套的dict展平dict列表,python,python-2.7,recursion,Python,Python 2.7,Recursion,我想把dict的列表弄平但有问题 比如说我有一份口述的清单 d = [{'val': 454,'c': {'name': 'ss'}, 'r': {'name1': 'ff'}},{'val': 'ss', 'c': {'name': 'ww'}, 'r': {'name1': 'ff'}}, {'val': 22,'c': {'name': 'dd'}, 'r': {'name1': 'aa'}}] 我想得到的结果是 d = [{'val': 454,'name': 'ss', 'name1

我想把dict的列表弄平但有问题

比如说我有一份口述的清单

d = [{'val': 454,'c': {'name': 'ss'}, 'r': {'name1': 'ff'}},{'val': 'ss', 'c': {'name': 'ww'}, 'r': {'name1': 'ff'}}, {'val': 22,'c': {'name': 'dd'}, 'r': {'name1': 'aa'}}]
我想得到的结果是

d = [{'val': 454,'name': 'ss', 'name1': 'ff'},{'val': 'ss','name': 'ww', 'name1': 'ff'},{'val': 22, 'name': 'dd', 'name1': 'aa'}]
为此,我使用以下函数

def flatten(structure, key="", flattened=None):
    if flattened is None:
        flattened = {}
    if type(structure) not in(dict, list):
        flattened[key] = structure
    elif isinstance(structure, list):
        for i, item in enumerate(structure):
            flatten(item, "%d" % i, flattened)
    else:
        for new_key, value in structure.items():
            flatten(value, new_key, flattened)
    return flattened

现在,我遇到的问题是,它只生成dict中的第一个元素

您可能在错误的位置初始化了某些内容。请看下面的代码:

d = [{'val': 454, 'c': {'name': 'ss'}, 'r': {'name1': 'ff'}}, {'val': 55, 'c': {'name': 'ww'}, 'r': {'name1': 'ff'}}, {'val': 22, 'c': {'name': 'dd'}, 'r': {'name1': 'aa'}}]
#                                                                     ^ typo here

def flatten(my_dict):
    res = []
    for sub in my_dict:
        print(sub)
        dict_ = {}
        for k, v in sub.items():
            if isinstance(v, dict):
                for k_new, v_new in v.items():
                    dict_[k_new] = v_new
            else:
                dict_[k] = v
        res.append(dict_)
    return res

result = flatten(d)
print(result)  # [{'name': 'ss', 'name1': 'ff', 'val': 454}, {'name': 'ww', 'name1': 'ff', 'val': 55}, {'name': 'dd', 'name1': 'aa', 'val': 22}]

如果
,则应将
展平
初始化为与
结构
相同的类型,并在
列表
案例中递归时传递

def flatten_2(structure, key="", flattened=None):
    if flattened is None:
        flattened = {} if isinstance(structure, dict) else []
    if type(structure) not in(dict, list):
        flattened[key] = structure
    elif isinstance(structure, list):
        for i, item in enumerate(structure):
            flattened.append(flatten(item, "%d" % i))
    else:
        for new_key, value in structure.items():
            flatten(value, new_key, flattened)
    return flattened

In [13]: flatten_2(d)
Out[13]: 
[{'name': 'ss', 'name1': 'ff', 'val': 454},
 {'name': 'ww', 'name1': 'ff', 'val': 'ss'},
 {'name': 'dd', 'name1': 'aa', 'val': 22}]

当然,这只适用于有限类型的数据。

问题是什么?问题是什么?你应该提到什么不起作用(正如预期的那样)。@Ev.Kounis我想奉承一个包含嵌套dict的dict列表,基本上,我不;我不想要嵌套的路径名,它们应该合并在同一个路径中dict@AshishNitinPatil补充问题我犯了一个错误,我在重复最初的问题,而不是在子问题上。谢谢你的帮助