在Python3中,有没有一种简单的方法可以按键对dict列表进行分组 我有一个复杂的输入列表,我想格式化
我的输入对象如下所示:
my_input = [
{
'name': 'nameA',
'departments': [
{
'name': 'dep1',
'details': [
{
'name': 'name_detA',
'tech_name': 'techNameA',
'others': None,
'sub_details': []
},
{
'name': 'name_detB',
'tech_name': 'techNameB',
'others': 22,
'sub_details': [
{
'id': 'idB',
'column2': 'ZZ',
'column3': 'CCC',
'column4': {
'id': 'id2',
'subColumn1': 'HHH',
'subColumn1': 'PPPP',
'subColumn1': 'FFFFFF'
}
}
]
},
{
'name': 'name_detB',
'tech_name': 'techNameB',
'others': 22,
'sub_details': [
{
'id': 'idA',
'column2': 'AA',
'column3': 'BBB',
'column4': {
'id': 'id1',
'subColumn1': 'XXXX',
'subColumn1': 'YYYYY',
'subColumn1': 'DDDDDD'
}
}
]
}
]
}
]
}
]
我的目标是将具有相同details['techName']
的元素分组到一个元素中,并合并它们的sub_details
预期产出:
my_output = [
{
"name": "nameA",
"departments": [
{
"name": "dep1",
"details": [
{
"name": "name_detA",
"tech_name": "techNameA",
"others": None,
"sub_details": []
},
{
"name": "name_detB",
"tech_name": "techNameB",
"others": 22,
"sub_details": [
{
"id": "idB",
"column2": "ZZ",
"column3": "CCC",
"column4": {
"id": "id2",
"subColumn1": "HHH",
"subColumn1": "PPPP",
"subColumn1": "FFFFFF"
}
},
{
"id": "idA",
"column2": "AA",
"column3": "BBB",
"column4": {
"id": "id1",
"subColumn1": "XXXX",
"subColumn1": "YYYYY",
"subColumn1": "DDDDDD"
}
}
]
}
]
}
]
}
]
我试过:
result_list = []
sub = []
for elem in my_input:
for data in elem["departments"]:
for sub_detail, dicts_for_that_sub in itertools.groupby(data["details"], key=operator.itemgetter("sub_details")):
sub.append({"sub_details": sub_detail})
print(sub)
但我正在努力创造新的产出
假设我在这里使用的输入是您真正想要的,那么您就走上了正确的轨道。我将最内层的for循环重新实现为对方法的调用,但这并不是严格需要的
我可能会对使用
setdefault()
而不是if
/else
的merge_details()
方法采取稍微不同的方法,但是如果您以前没有使用过setdefault()
,那么这种方法更容易遵循import json
只是为了让打印效果“好”,而不是解决方案的一部分相关问题 更多 >
编程相关推荐