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}
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.
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.
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)).
Two ways (assuming Python 3.6):
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)])
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)])
from itertools import chain from collections import OrderedDict OrderedDict(chain(a.items(), b.items()))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With