如何在python中合并2个有序词典?

时间:2017-08-31 01:04:29

标签: python dictionary

我有2个有序词典,例如:

a = collections.OrderedDict()
b = collections.OrderedDict()

他们有东西。我如何合并这两个?我试过了:

mergeDict = dict(a.items() + b.items())

但这样做不再是有序词典了。

我正在寻找,如果a = {1,2,5,6}并且b = [0,7,3,9}然后mergeDict = {1,2,5,6,0,7,3, 9}

4 个答案:

答案 0 :(得分:11)

两种方式(假设Python 3.6):

  1. 使用"更新方法"。假设有两个词典:

    >>> d1 = collections.OrderedDict([('a', 1), ('b', 2)])
    >>> d2 = {'c': 3, 'd': 4}
    >>> d1.update(d2)
    >>> d1
    OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
    
  2. 使用'连接运算符(+)'

    的第二种方法
    >>> d1 = collections.OrderedDict([('a', 1), ('b', 2)])
    >>> d2 = {'c': 3, 'd': 4}
    >>> d3 = collections.OrderedDict(list(d1.items()) + list(d2.items()))
    >>> d3
    OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])
    

答案 1 :(得分:6)

from itertools import chain
from collections import OrderedDict
OrderedDict(chain(a.items(), b.items()))

答案 2 :(得分:2)

CPython 3.6和任何3.7+解释器已经保留了字典键顺序。 这使您可以使用{**a, **b}语法。

例如:

>>> a = {1: "AA", 2: "BB", 5: "CC", 6: "DD"}
>>> b = {0: "EE", 7: "FF", 3: "GG", 9: "HH"}
>>> {**a, **b}
{1: 'AA', 2: 'BB', 5: 'CC', 6: 'DD', 0: 'EE', 7: 'FF', 3: 'GG', 9: 'HH'}

答案 3 :(得分:0)

而不是dict使用OrderedDict for mergeDict

mergeDict = collections.OrderedDict(a.items() + b.items())

备注:这仅适用于python 2.x,在dict.items()上为python 3添加list()因为dict.items()不再返回支持+操作的列表

或在评论

中使用@alfasin提及的a.update(b)

我尝试用简单的例子,这两种方法对我来说都很好

相关问题