Home > Software design >  How do I merge dictionaries having similar values in Python?
How do I merge dictionaries having similar values in Python?

Time:09-17

I have a problem.

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}]

I will compare in this array. If the same name, I will combine all value of this dict.

It mean combine all value of key 'point'. I will have key list 'point' with multi dict

We have many duplicate key name = 'cpu'. So I will combine all value if the same value.U see we have PO the same value (PO=3 with name=cpu).If different value, we will take the last value(last value 'date':'2021-09-15').Finally, we will append the dicts in the key point list together

Desired result

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}
      ]

Note: I use python 3.6

I hope someone will help me. Thank you very muck

CodePudding user response:

There is probably a better way to do this but the following works:

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)
  • Related