William
William

Reputation: 4028

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': {'CafeVersion': '2807'}}, 

      {'CafeData': {'IsSoftwareOnly': '1'}}, 

      {'CafeData'{'IsPassportTCPIP': '1'}} 

]

The output should like this:

 [ {'SNAPSHOT': {'SnapshotVersion': '304','SnapshotCreationDate': '2015-06-21 17:33:41'}},

   {'CafeData': {'CafeVersion': '2807','IsSoftwareOnly': '1','IsPassportTCPIP': '1'}} 
 
]

Upvotes: 5

Views: 123

Answers (2)

Shruti Singhal
Shruti Singhal

Reputation: 76

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)

Upvotes: 1

mechanical_meat
mechanical_meat

Reputation: 169304

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'}})

Upvotes: 8

Related Questions