【问题标题】:Merge two nested OrderedDicts in Python在 Python 中合并两个嵌套的 OrderedDicts
【发布时间】:2015-12-01 13:27:32
【问题描述】:

Comparing/combining two dictionaries 开始,我正在尝试研究如何合并两个嵌套的 OrderedDicts。

我拥有的数据类似于这样的简化形式:

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), 
                      ])
         )
    ] 
) 

我想将'personA''personB' 合并到一个新的output 变量中,键为personA(假设它们实际上是同一个人)。

到目前为止,我已经尝试过这段代码,但所有值都以列表形式结束。我不介意是否覆盖任何数据,但输出必须包含相同的数据结构:

output = collections.OrderedDict()
for k,e in personA.items()+personB.items():
    output.setdefault(k,[]).append(e) 

【问题讨论】:

    标签: python dictionary merge ordereddictionary


    【解决方案1】:

    如果我很好理解你的问题,你想要这样的东西:

    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()]))
        ])
    

    你也可以达到同样的效果:

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

    并验证结果:

    >>> new_dict == newd
    >>> True
    

    【讨论】:

      猜你喜欢
      • 2012-08-31
      • 1970-01-01
      • 2017-12-07
      • 2016-03-27
      • 2017-09-25
      • 2017-08-24
      • 1970-01-01
      • 1970-01-01
      • 2020-11-28
      相关资源
      最近更新 更多