Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge different key of single Dictionary to one key in Python

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

like image 535
Amiclone Avatar asked Oct 23 '25 17:10

Amiclone


1 Answers

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'}}
}
like image 157
timgeb Avatar answered Oct 26 '25 07:10

timgeb