How to Merge and Sort dictionaries

By | 14th June 2021

In Python, we can merge two dictionary objects very easily. First, we create two dictionaries then we can merge and sort the dictionaries based on the values. In python 2.x we can use the following code,

Python 2.x

print("Example for merging dictionaries")
print("Creation of dic1")
dic1={'key1':1, 'key2':2}
print(dic1)
print("Creation of dic2")
dic2={'key3':3, 'key4':4}
print(dic2)
dic3=dict(dic1, **dic2)
print("Before Sorting")
print(dic3)
sorted(dic3.items(), key=lambda x: x[1])
print("After Sorting")
print(dic3)
Output:
Example for merging dictionaries
Creation of dic1
{'key2':2, 'key1':1}
Creation of dic2
{'key3':3, 'key4':4}
Before Sorting
{'key3': 3, 'key2': 2, 'key1': 1, 'key4': 4}
After Sorting
[('key1', 1), ('key2', 2), ('key3', 3), ('key4', 4)]

In the below example, the two dictionaries are created and then merge the dictionary keys with the values. After that, we can sort the keys based on the values.

Python 3.x

Method: 1

print("Example for merging dictionaries")
print("creation of dic1")
dic1={'key1':4, 'key2':7}
print(dic1)
print("Creation of dic2")
print(dic2)
dic2={'key3':8, 'key4':6}
dic3={**dic1, **dic2}
print("Before Sorting")
print(dic3)
sorted(dic3.items(), key=lambda x: x[1])
print("After sorting")
print(dic3)

Method: 2

By using the operator function, we can use the below code. But, the output will be the same for both the codes.

import operator 
print("Example for merging dictionaries")
print("creation of dic1")
dic1={'key1':4, 'key2':7}
print(dic1)
print("Creation of dic2")
print(dic2)
dic2={'key3':8, 'key4':6}
dic3={**dic1, **dic2}
print("Before Sorting")
print(dic3)
sorted(dic3.items(), key=operator.itemgetter(1))
print("After sorting")
print(dic3)
Output:
Example for merging dictionaries
Creation of dic1
{'key1':4, 'key2':7}
Creation of dic2
{'key3':8, 'key4':6}
Before Sorting
{'key1': 4, 'key2': 7, 'key3': 8, 'key4': 6}
After Sorting
[('key1', 4), ('key4', 6), ('key2', 7), ('key3', 8)]