I have a dictionary like:
d = {
'S1': {
'S11': {'first': 'a', 'second': 'b'},
'S12': {'first': 'c', 'second': 'd'}
},
'S2': {
'S21': {'first': 'l', 'second': 'e'},
'S22': {'first': 'd', 'second': 't'}
},
'S3': {
'S31': {'first': 'z', 'second': 'p'},
'S32': {'first': 'x', 'second': 'g'}
}
}
I want to merge this dict like:
{
'S': {
'S11': {'first': 'a', 'second': 'b'},
'S12': {'first': 'c', 'second': 'd'},
'S21': {'first': 'l', 'second': 'e'},
'S22': {'first': 'd', 'second': 't'},
'S31': {'first': 'z', 'second': 'p'},
'S32': {'first': 'x', 'second': 'g'}
}
}
The problem is in actual I have s1, s2, s3.....s100 and my current method is not very clear. Could someone please suggest a better way to achieve this?
Thanks
Use a ChainMap.
>>> from collections import ChainMap
>>> c = {'S': ChainMap(*d.values())}
>>> c['S']['S32']
{'first': 'x', 'second': 'g'}
You could convert the ChainMap back to a dict, if you like.
>>> c = {'S': dict(ChainMap(*d.values()))}
>>> c
{'S': {
'S31': {'first': 'z', 'second': 'p'},
'S32': {'first': 'x', 'second': 'g'},
'S21': {'first': 'l', 'second': 'e'},
'S22': {'first': 'd', 'second': 't'},
'S11': {'first': 'a', 'second': 'b'},
'S12': {'first': 'c', 'second': 'd'}}
}
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