Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge 2 ordered dictionaries in python?

I have 2 ordered dictionaries, like:

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

And they have stuff in them. How do I merge these 2? I tried:

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

but doing this it's not a ordered dictionary anymore.

What I am looking for: if a = {1, 2, 5, 6} and b = [0, 7, 3, 9} then mergeDict = {1, 2, 5, 6, 0, 7, 3, 9}

like image 262
golu Avatar asked Aug 31 '17 01:08

golu


People also ask

Can we merge two dictionaries in Python?

Using | in Python 3.9 In the latest update of python now we can use “|” operator to merge two dictionaries. It is a very convenient method to merge dictionaries.

How do I merge two dictionaries in a program?

Merge two dictionaries using Copy() and Update() Method In this method, we copy all the elements of the first dictionary (d1) elements using the copy() function and then assign the copied data into the other dictionary (d3). After that, we update the dictionary d3 with the d2 dictionary using the update() function.

How do I concatenate a dictionary in Python?

Python concatenate dictionaries with same keys The counter holds the data in an unordered collection just like a hashable object. To concatenate the dictionary, I have used dictionary = dictionary1 + dictionary2. To get the output, I have used print(“dictionary”, str(dictionary)).


2 Answers

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)]) 
like image 144
SalN85 Avatar answered Oct 04 '22 08:10

SalN85


from itertools import chain from collections import OrderedDict OrderedDict(chain(a.items(), b.items())) 
like image 35
Neil G Avatar answered Oct 04 '22 08:10

Neil G