Python-追加/合并字典列表

问题描述 投票:1回答:1

我正在尝试在其中包含列表的单个词典列表之间合并一些数据。如果匹配,将基于“对象”键进行合并。如果匹配相同的值,还将添加到其给定的“部分”中。给定以下数据:

data = [
        {
         "semver":"1.0.0",
         "sections":[
            {
               "name":"Add",
               "messages":[
                  "add: comment here"
               ]
            }
         ],
         "object":"files.sh"
      },
      {
         "semver":"1.0.0",
         "sections":[
            {
               "name":"Add",
               "messages":[
                  "add: Second comment here"
               ]
            }
         ],
         "object":"files.sh"
      },
      {
         "semver":"1.0.0",
         "sections":[
            {
               "name":"Fix",
               "messages":[
                  "Comment here"
               ]
            }
         ],
         "object":"files.sh"
      }
]

我希望最终实现这一目标

data = [
        {
         "semver":"1.0.0",
         "sections":[
            {
               "name":"Add",
               "messages":[
                  "add: comment here",
                  "add: Second comment here"
               ]
            },
            {
               "name":"Fix",
               "messages":[
                  "Fix: comment here"
               ]
            }
         ],
         "object":"files.sh"
      },
]

for item in data:
    for k, v  in item.items():
        print(k)
        print(v)

任何指针或帮助将不胜感激。到目前为止,我遍历了字典中的每个k,v对,但是无法将我的头缠在循环中两者之间的匹配上。

再次感谢

python list dictionary merge append
1个回答
0
投票

下面的代码将为您完成任务,但是请注意,这可能不是最省时的方法,如果您无法使所有字典中的键都保持一致,则可能会遇到一些键错误。

d = []
for x in data:
    for y in d:
        if x['object'] == y['object']:
            for section in x['sections']:
                for sectiony in y['sections']:
                    if section['name'] == sectiony['name']:
                        sectiony['messages'].extend(x for x in\
                                section['messages'] if x not in sectiony['messages'])
                        break
                else:
                    y['sections'].append(section)
            break
    else:
        d.append(x)

输出

[
    {
        "semver": "1.0.0",
        "object": "files.sh",
        "sections": [
            {
                "messages": [
                    "add: comment here",
                    "add: Second comment here"
                ],
                "name": "Add"
            },
            {
                "messages": [
                    "Comment here"
                ],
                "name": "Fix"
            }
        ]
    }
]
© www.soinside.com 2019 - 2024. All rights reserved.