Я расширяю свой оригинальный вопрос здесь: Как добавить / объединить список словарей? .
Я пытаюсь объединить некоторые данные между одним списком словарей, который имеет списки внутри. Слияние будет происходить на основе ключей «объект» и «semver», если они совпадают. Также добавляем к их данному «разделу», если совпадает одно и то же значение. Учитывая следующие данные:
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"
},
{
"semver":"2.0.0",
"sections":[
{
"name":"Fix",
"messages":[
"2.0.0 Fix Comment here"
]
}
],
"object":"files.sh"
},
{
"semver":"2.0.0",
"sections":[
{
"name":"Add",
"messages":[
"2.0.0 Add Comment here"
]
}
],
"object":"files.sh"
},
{
"semver":"2.0.0",
"sections":[
{
"name":"Add",
"messages":[
"2.0.0 comment for the NewFile"
]
}
],
"object":"NewFile.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"
},
{
"semver":"2.0.0",
"sections":[
{
"name":"Add",
"messages":[
"2.0.0 Add comment here",
]
},
{
"name":"Fix",
"messages":[
"2.0.0 Fix Comment here"
]
}
],
"object":"files.sh"
},
{
"semver":"2.0.0",
"sections":[
{
"name":"Add",
"messages":[
"2.0.0 comment for the NewFile"
]
}
],
"object":"NewFile.sh"
},
]
Кодовый блок
objects = {} # mapping for object: object_data with sections
sections = defaultdict(list) # mapping for object: all sections
for d in data:
print(d["semver"])
for k, v in list(d.items()):
if v == d["semver"]:
try:
section = d.pop("sections")
sections[d["object"]].extend(section)
objects[d["object"]] = d # populate with object data without sections
except Exception as e:
print(e)
pass
output = []
for object_name, object_data in objects.items():
object_data["sections"] = sections[object_name]
output.append(object_data)
До сих пор я перебираю каждая пара k, v в dict
, но не может обернуться вокруг совпадения между двумя версиями и добавления к этому конкретному c dict
в l oop.