我正在尝试在其中包含列表的单个词典列表之间合并一些数据。如果匹配,将基于“对象”键进行合并。如果匹配相同的值,还将添加到其给定的“部分”中。给定以下数据:
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对,但是无法将我的头缠在循环中两者之间的匹配上。
尝试这个:
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
下面的代码将为您完成任务,但是请注意,这可能不是最省时的方法,如果您无法使所有字典中的键都保持一致,则可能会遇到一些键错误。如果键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"
}
]
}
]