How to Sort a Dictionary by Value in Python

python_tutorials

Introduction

A dictionary in Python is a collection of items that stores data as key-value pairs. In Python 3.7 and later versions, dictionaries are sorted by the order of item insertion. In earlier versions, they were unordered.

Let’s have a look at how we can sort a dictionary on basis of the values they contain.

Sort Dictionary Using a for Loop

We can sort a dictionary with the help of a for loop. First, we use the sorted() function to order the values of the dictionary. We then loop through the sorted values, finding the keys for each value. We add these keys-value pairs in the sorted order into a new dictionary.

Note: Sorting does not allow you to re-order the dictionary in-place. We are writing the ordered pairs in a completely new, empty dictionary.

dict1 = {1: 1, 2: 9, 3: 4}
sorted_values = sorted(dict1.values())

 

 

To finish reading, please visit source site