0

Following on from Comparing/combining two dictionaries, I am trying to work out how to merge two nested OrderedDicts.

The data I have resembles something like this, in simplified form:

personA = OrderedDict([
         (u'score',
          OrderedDict([(u'2015-09-09 03:40:33 +0100', 2646), 
                       (u'2015-09-10 03:35:34 +0100', 2646), 
                      ])
         ),

         (u'adjusted_score',
          OrderedDict([(u'2015-09-09 03:40:33 +0100', 3646), 
                       (u'2015-09-10 03:35:34 +0100', 3646), 
                      ])
         )
    ]
)  

personB = OrderedDict([
         (u'score',
          OrderedDict([(u'2015-09-11 03:40:33 +0100', 4646), 
                       (u'2015-09-12 03:35:34 +0100', 4646), 
                      ])
         ), 

         (u'adjusted_score',
          OrderedDict([(u'2015-09-11 03:40:33 +0100', 5646), 
                       (u'2015-09-12 03:35:34 +0100', 5646), 
                      ])
         )
    ] 
) 

I want to merge both 'personA' and 'personB' into one new output variable, with a key of personA (let's imagine that they are in fact the same person).

So far I've tried this code but all values end up in lists. I don't mind if any data is overwritten, but the output must contain the same data structure:

output = collections.OrderedDict()
for k,e in personA.items()+personB.items():
    output.setdefault(k,[]).append(e) 
Community
  • 1
  • 1
user2761030
  • 1,385
  • 2
  • 20
  • 33

1 Answers1

0

If I well understood your question you want something like :

new_dict = OrderedDict([
    ('score',
     OrderedDict([(k, v) for k,v in personA['score'].items()]
         + [(k, v) for k,v in personB['score'].items()])), 
    ('adjusted_score',
     OrderedDict([(k, v) for k,v in personA['adjusted_score'].items()]
         + [(k, v) for k,v in personB['adjusted_score'].items()]))
    ])

You can also achieve the same result doing :

newd = OrderedDict()
for k in personA.keys():
    newd[k] = OrderedDict(
        [i for i in personA[k].items()] + [j for j in personB[k].items()]
    )

And verify the result:

>>> new_dict == newd
>>> True
mgc
  • 5,223
  • 1
  • 24
  • 37