Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'}} 
 
]
like image 340
William Avatar asked Dec 31 '22 15:12

William


1 Answers

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'}})
like image 50
mechanical_meat Avatar answered Feb 02 '23 01:02

mechanical_meat