How to merge 2 ordered dictionaries in python?

Two ways (assuming Python 3.6):

  1. Use “update method”. Suppose there are two dictionaries:

    >>> 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. Second method using ‘concatenation operator (+)’

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

Leave a Comment