简体   繁体   English

包含多个字典列表的嵌套字典

[英]Nested dictionary with lists to many dictionaries

I have nested dictionary with lists like this我有这样的列表嵌套字典

    {
     'a': 1,
     'x':[
          {'b': 1,
           'c': [
             {'z': 12},
             {'z': 22},
            ]
          },
          {'b': 2,
           'c': [
              {'z': 10},
              {'z': 33},
            ]
          }
        ]
     }

And I want to convert it to list of flat dictionaries i form like this.我想将它转换为我这样形成的平面词典列表。

[
 {'a': 1, 'b': 1, 'z': 12},
 {'a': 1, 'b': 1, 'z': 22},
 {'a': 1, 'b': 2, 'z': 10},
 {'a': 1, 'b': 2, 'z': 33},
]

Any idea how to achieve that?知道如何实现这一目标吗?

A possible solution is:一个可能的解决方案是:

#!/usr/bin/env python3
d = {
    'a': 1,
    'x': [
        {
            'b': 1,
            'c': [
                {'z': 12}
            ]
        },
        {
            'b': 2,
            'c': [
                {'z': 10}
            ]
        }
    ]
}

res = [{"a": 1, "b": x["b"], "z": x["c"][0]["z"]} for x in d["x"]]
print(res)

This assumes that there is only one a (with a fixed value of 1 ) and x element and this element is added to the comprehension manually.这假设只有一个a (固定值为1 )和x元素,并且这个元素被手动添加到理解中

The other two elements ( b and z ) are taken from x array with a list comprehension.其他两个元素( bz )从带有列表推导式的x数组中获取。

To learn more about how comprehensions work read the following:要了解有关理解如何工作的更多信息,请阅读以下内容:

PS.附注。 You are supposed to first show what you have tried so far and get help on that.您应该首先展示到目前为止您尝试过的内容并获得帮助。 Take a look at SO rules before posting your next question.在发布下一个问题之前,请查看SO 规则

The following produces the requested result:以下生成请求的结果:

[{'a': 1, 'b': 1, 'z': 12}, {'a': 1, 'b': 2, 'z': 10}]

Use at your own risk.使用风险自负。 The following was only tested on your example.以下仅在您的示例上进行了测试。

from itertools import product

def flatten(D):

    if not isinstance(D, dict): return D

    base = [(k, v) for k, v in D.items() if not isinstance(v, list)]
    lists = [[flatten(x) for x in v] for k, v in D.items() if isinstance(v, list)]

    l = []
    for p in product(*lists):
        r = dict(base)
        for a in p:
            for d in a:
                r.update(d)
        l.append(r)

    return l

The following tests above.以上测试如下。

d = {
     'a': 1,
     'x':[
          {'b': 1,
           'c': [
             {'z': 12}
            ]
          },
          {'b': 2,
           'c': [
              {'z': 10}
            ]
          }
        ]
     }

print flatten(d)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将字典扁平化为列表字典的嵌套字典 - flattened dictionary into nested dictionary of dictionaries of lists 列表中有很多字典VS字典,列表很少? - List with many dictionaries VS dictionary with few lists? 来自字典的Pandas DataFrame,带有嵌套的字典列表 - Pandas DataFrame from dictionary with nested lists of dictionaries 从带有嵌套字典的列表字典中提取值 - Extracting values from Dictionary of lists with nested dictionaries 将带有字典列表的嵌套字典转换为 Pandas DataFrame - Convert a nested dictionary with lists of dictionaries to a Pandas DataFrame 使用包含包含字典的列表的嵌套字典从字典中提取数据 - extract data from dictionary with nested dictionaries that contain lists that contain dictionaries 使用嵌套列表或来自 2 个列表的字典创建分层字典 - Creating a hierarchical dictionary with nested lists or dictionaries from 2 lists 如何将两个嵌套字典比较并合并到另一个嵌套列表字典中? - How to compare and merge two nested dictionaries into another nested dictionary of lists? 为字典列表的嵌套字典中的每个递归项目提供一个ID - Providing an id for each recursed item in nested dictionary of lists of dictionaries 如何使用 Python 将三个字典列表合并为一个嵌套字典 - How to merge three lists of dictionaries into one nested dictionary using Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM