如何合并两个list[dict]并按其ID正确排序?

2024-09-23 08:29:02 发布

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

我正在尝试将两个list[dict]合并为以下格式,并对这两种技术和子技术进行排序,但我不确定如何在不影响其他技术的情况下正确地连接它们

techniques = [{
   "technique_id":"T1548",
   "technique":"demo",
   "url":"url",
   "tactic":[
      "demo",
      "demo"
   ]
}]


subtechniques = [{
   "technique_id":"T1548.002",
   "technique":"demo",
   "url":"url"
}]


def merge_techniques(techniques, subtechniques):
    change_list = []
    for x in techniques:
        for y in subtechniques:
            if x['technique_id'] == y['technique_id'].split('.')[0]:
                print(x)
                print(y)
    return change_list


merge_techniques(techniques, subtechniques)

期望输出

{
   "technique_id":"T1548",
   "technique":"dmep",
   "url":"https://xxxxxxxxxxxx",
   "tactic":[
      "xxxxxxxxxxxx",
      "xxxxxxxxxxxx"
   ],
   "subtechnique": [
       {
        "technique_id":"T1548.002",
        "technique":"demo",
        "url":"url"
       }
    ]
}

Tags: inidurlfordemomergechange技术
1条回答
网友
1楼 · 发布于 2024-09-23 08:29:02

如果不想创建新对象,可以放弃复制操作

import copy

def merge_techniques(techniques, subtechniques):
    result = []
    # create technique_id dictionary
    techniques_dict = dict()
    for tech in techniques:
        # create new object
        tech_copy = copy.copy(tech)
        
        techniques_dict[tech['technique_id']] = tech_copy
        result.append(tech_copy)
    
    # visit all sub techniques
    for subtech in subtechniques:
        tech_id = subtech['technique_id'].split('.')[0]
        
        # search by tech_id 
        if tech_id not in techniques_dict:
            # if not found
            print('Tech %s is not found'%(tech_id))
            continue
        
        # get tech by tech_id
        tech = techniques_dict[tech_id]
        
        # create subtechnique array if not existed
        if 'subtechnique' not in tech:
            tech['subtechnique'] = []
            
        # copy subtech object
        tech['subtechnique'].append(copy.copy(subtech))
    
    return result

相关问题 更多 >