如何合并 Python 中具有相似值的字典?

How do I merge dictionaries having similar values in Python?

我有问题。

Input=[
{'id':uuid1(),'name':'mem','point':[{'second':0,'severity':'infor'}],'date':'2021-09-15','PO':5},
{'id':uuid1(),'name':'cpu','point':[{'second':10,'severity':'warning'}],'date':'2021-09-13','PO':3},
{'id':uuid1(),'name':'cpu','point':[{'second':20,'severity':'critical'}],'date':'2021-09-14','PO':3},
{'id':uuid1(),'name':'cpu','point':[{'second':30,'severity':'infor'}],'date':'2021-09-15','PO':3}]

我将在这个数组中进行比较。如果同名,我会合并这个字典的所有值。

意思是组合键'point'的所有值。我将有键列表 'point' 和 multi dict

我们有很多重复的键名 = 'cpu'。因此,如果相同 value.U 看到我们有相同的值(PO=3 和名称=cpu),我将合并所有值。如果值不同,我们将采用最后一个值(最后一个值 'date':'2021-09-15').最后我们将关键点列表中的dicts追加在一起[=13​​=]

想要的结果

Output=[
{'id':uuid1(),'name':'mem','point':[{'second':0,'severity':'infor'}],'date':'2021-09-15','PO':5},
{'id':uuid1(),'name':'cpu','point':[{'second':10,'severity':'warning'},
                                    {'second':20,'severity':'critical'},
                                    {'second':30,'severity':'infor'}],'date':'2021-09-15','PO':3}
      ]

注:我用的是python3.6

希望有人能帮助我。非常感谢muck

可能有更好的方法来执行此操作,但以下方法有效:

a=[{'name':'mem','point':[{'second':0,'severity':'infor'}],'date':'2021-09-15','PO':5},
{'name':'cpu','point':[{'second':10,'severity':'warning'}],'date':'2021-09-13','PO':3},
{'name':'cpu','point':[{'second':20,'severity':'critical'}],'date':'2021-09-14','PO':3},
{'name':'cpu','point':[{'second':30,'severity':'infor'}],'date':'2021-09-15','PO':3}]

b=[]
    
for i in a:
    for j in b: 
        if i['name'] == j['name']:
            j['point'] += i['point']
            break
    else:
        b.append(i)