如何附加/合并词典列表?

2024-04-29 06:42:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将一些数据合并到一个包含列表的字典列表中。如果“对象”键匹配,则会根据它们进行合并。如果相同的值匹配,也会添加到给定的“部分”。鉴于以下数据:

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)

任何指点或帮助都将不胜感激。到目前为止,我正在通过dict中的每个k,v对进行循环,但我不能在循环中的两个对之间的匹配上绞尽脑汁


Tags: 数据nameadd列表datahereobjectsh
2条回答

下面的代码将为您完成此任务,但请注意,这可能不是执行此任务的最佳方式,如果您的所有目录中的键不一致,您可能会遇到一些键错误。 此外,如果在dicts中将semver键作为不同的值与object的值匹配,则会丢失数据

d = []
for x in data:
    for y in d:
        if x['object'] == y['object']:
            for section_x in x['sections']:
                for section_y in y['sections']:
                    if section_x['name'] == section_y['name']:
                        section_y['messages'].extend(x for x in\
                                section_x['messages'] if x not in section_y['messages'])
                        break
                else:
                    y['sections'].append(section_x)
            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"
            }
        ]
    }
]

试试这个:

import json # just for pretty print, you don't have to use it
from collections import defaultdict

objects = {} # mapping for object: object_data with sections
sections = defaultdict(list) mapping for object: all sections
for d in data:
    section = d.pop("sections")
    sections[d["object"]].extend(section)  # extends the sections for the object
    objects[d["object"]] = d  # # populate with object data without sections

# merge between sections and objects by object key
output = []
for object_name, object_data in objects.items():
    object_data["sections"] = sections[object_name]
    output.append(object_data)
print(json.dumps(output,indent=4)) # just for pretty print

相关问题 更多 >