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'}}
]
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'}})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With