Programming

Merge two dictionaries and sort the values in Python

Suppose you have two different dictionaries in Python and you need to convert them into one dictionary. It’s easy to do.

But you also need to sort the values of the dictionaries. And here is the tricky part. It’s also easy to do if you know the right way.

Like I have two dictionaries in Python. First one is dict1 = {"zero":0,"two":2, "four":4, "six": 6, "eight":8,"ten":10} this one and the second dictionary is dict2 = {"one":1,"three":3,"five":5,"seven":7, "nine":9}.

Read More: How to uninstall Perl in Linux 

Now if I want to convert these two dictionaries into one I just need to create another variable and merge the two dictionaries like this.

dict3 = {**dict1, **dict2}

But now comes the tricky part. Now I need to sort them. To sort the values I will use the sorted function. I will give the dictionary items as iterable. Because in the sorted function iterable is required. Then I will give key value because it decides the sorted order. It’s an optional value but in my case, we need to give it. I will pass a lambda function here. The code will be like that: sorted(dict3.items(), key=lambda x:x[1]) and at the end, we need to convert this into a dictionary because after applying the sorted function it will give us a list.

In the end, the final code will look like this.

dict1 = {"zero":0,"two":2, "four":4, "six": 6, "eight":8,"ten":10}
dict2 = {"one":1,"three":3,"five":5,"seven":7, "nine":9}
dict3 = {**dict1, **dict2}
dict3 = dict(sorted(dict3.items(), key=lambda x:x[1]))
print(dict3)

And the output will be this.

{'zero': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9, 'ten': 10}

What is your reaction?

0
Excited
0
Happy
0
In Love
0
Not Sure
0
Silly

Leave a reply

Your email address will not be published. Required fields are marked *