Я пытаюсь объединить объект на основе ключа specs
, большая часть структуры ключей является согласованной, учитывая, что объединение произойдет только в том случае, если company_name
совпадает (в этом примере у меня только одинcompany_name
) и если только (имя, {цвет, тип, лицензия, описание) равны для нескольких списков.
[
{
"company_name": "GreekNLC",
"metadata": [
{
"name": "Bob",
"details": [
{
"color": "black",
"type": "bmw",
"license": "4DFLK",
"specs": [
{
"properties": [
{
"info": [
"sedan",
"germany"
]
},
{
"info": [
"drive",
"expensive"
]
}
]
}
],
"description": "amazing car"
}
]
},
{
"name": "Bob",
"car_details": [
{
"color": "black",
"type": "bmw",
"license": "4DFLK",
"specs": [
{
"properties": [
{
"info": [
"powerful",
"convertable"
]
},
{
"info": [
"drive",
"expensive"
]
}
]
}
],
"description": "amazing car"
}
]
}
]
}
]
Я ожидаю следующий вывод:
[
{
"company_name": "GreekNLC",
"metadata": [
{
"name": "Bob",
"details": [
{
"color": "black",
"type": "bmw",
"license": "4DFLK",
"specs": [
{
"properties": [
{
"info": [
"powerful",
"convertable"
]
},
{
"info": [
"sedan",
"germany"
]
},
{
"info": [
"drive",
"expensive"
]
}
]
}
],
"description": "amazing car"
}
]
}
]
}
]
Код, который у меня есть,
headers = ['color', 'license', 'type', 'description']
def _key(d):
return [d.get(i) for i in headers]
def get_specs(b):
_specs = [c['properties'] for i in b for c in i['specs']]
return [{"properties": [i for b in _specs for i in b]}]
def merge(d):
new_merged_list = [[a, list(b)] for a, b in groupby(sorted(d, key=_key), key=_key)]
k = [{**dict(zip(headers, a)), 'specs': get_specs(b)} for a, b in new_merged_list]
return k
result = {'name': merge(c.get("details")) for i in data for c in i.get("metadata")}
print(json.dumps(result))
, но он не работает.Я получаю это
{"name": [{"color": "black", "specs": [{"properties": [{"info":
["amazing", "strong"]}]}]}]}