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 abs()
Python Strings
Python strftime()
Python String istitle()
Python Program to Parse a String to a Float or Int
Python Modules
Python Program to Get the Full Path of the Current Working Directory
Python Get Current time
Python Dictionary fromkeys()
Python Program to Iterate Over Dictionaries Using for Loop
Python String encode()
Python bytearray()
Python Program to Find the Size (Resolution) of a Image
Python globals()
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python String isupper()
Python map()
Python Set remove()
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python type()
Python String rfind()
Python Program to Find the Sum of Natural Numbers
Python bool()
Python Package
Python sleep()
Python Set intersection_update()
Machine Learning Applications Using Python - Cases studies form Healthcare, Retail, and Finance - Pu...
Python input()
Python Program to Extract Extension From the File Name
Python String isnumeric()
Python Program to Calculate the Area of a Triangle
Python String replace()