Skip to content Skip to sidebar Skip to footer

How To Merge Dictionary Having Same Keys

I have a data structure like this: [ {'SNAPSHOT': {'SnapshotVersion': '304'}}, {'SNAPSHOT': {'SnapshotCreationDate': '2015-06-21 17:33:41'}}, {'CafeData': {'Cafe

Solution 1:

Using https://docs.python.org/3/library/collections.html#collections.defaultdict which creates a dict within the defaultdict anytime a new key is encountered.

import collections as co

dd = co.defaultdict(dict)

l = [ {'SNAPSHOT': {'SnapshotVersion': '304'}},
      {'SNAPSHOT': {'SnapshotCreationDate': '2015-06-21 17:33:41'}},
      {'CafeData': {'CafeVersion': '2807'}}, 
      {'CafeData': {'IsSoftwareOnly': '1'}}, 
      {'CafeData': {'IsPassportTCPIP': '1'}} ]

for i in l: 
    for k,v in i.items(): 
        dd[k].update(v) 

Result:

In [8]: dd
Out[8]: 
defaultdict(dict,
            {'SNAPSHOT': {'SnapshotVersion': '304',
              'SnapshotCreationDate': '2015-06-21 17:33:41'},
             'CafeData': {'CafeVersion': '2807',
              'IsSoftwareOnly': '1',
              'IsPassportTCPIP': '1'}})

Solution 2:

l = [ 
      {'SNAPSHOT': {'SnapshotVersion': '304'}},
      {'SNAPSHOT': {'SnapshotCreationDate': '2015-06-21 17:33:41'}},
      {'CafeData': {'CafeVersion': '2807'}}, 
      {'CafeData': {'IsSoftwareOnly': '1'}}, 
      {'CafeData': {'IsPassportTCPIP': '1'}} 
]

mrgdict={}
    
for d in l:
    for key, value in d.items():
        if key in mrgdict:
            mrgdict[key].update(value)
        else:
            mrgdict[key]=value

dict={}
l1=[]
    
for key,value in mrgdict.items():
    dict[key]=value
    l1.append(dict)
    dict={}
print(l1)

Post a Comment for "How To Merge Dictionary Having Same Keys"