Table of Contents
In this example, you will learn to sort a Python dictionary by value.
To understand this example, you should have the knowledge of the following Python programming topics:
1. Example 1: Sort the dictionary based on values
dt = {5:4, 1:6, 6:3}
sorted_dt = {key: value for key, value in sorted(dt.items(), key=lambda item: item[1])}
print(sorted_dt)
Output
{6: 3, 5: 4, 1: 6}
- Here,
key=lambda item: item[1]returns the values of each key:value pair. - From each key:value pair of
dt.item(),sorted()sorts the items based on values.
Learn more about sorted() and its parameter key at Python sorted().
2. Example 2: Sort only the values
dt = {5:4, 1:6, 6:3}
sorted_dt_value = sorted(dt.values())
print(sorted_dt_value)
Output
[3, 4, 6]
In this example, sorted() is used for sorted values only. The values are fed into sorted() using dt.values().
Related posts:
Python bytes()
Python List append()
Python issubclass()
Python if...else Statement
Python Program to Compute all the Permutation of the String
Python Sets
Python Program to Print Output Without a Newline
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python List reverse()
Python List sort()
Python del Statement
Python Program to Find the Factors of a Number
Python Program to Check Leap Year
Python Program to Check Prime Number
Python String index()
Python Statement, Indentation and Comments
Python iter()
Python Program to Get File Creation and Modification Date
Python Program to Find Hash of File
Python Dictionary copy()
Python pow()
Python Program to Merge Mails
Python List copy()
Python Set pop()
Python tuple()
Python Program to Check the File Size
Java Program to Implement the Program Used in grep/egrep/fgrep
Python classmethod()
Python Program to Convert Two Lists Into a Dictionary
Python Program to Compute the Power of a Number
Python dict()
Python Program to Display Powers of 2 Using Anonymous Function