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 Program to Find the Square Root
Python hex()
Python Program to Find the Factorial of a Number
Python Input, Output and Import
Python int()
Python *args and **kwargs
Python float()
Python Program to Find the Sum of Natural Numbers
Python Program to Get a Substring of a String
Python Set issuperset()
Python Program to Merge Two Dictionaries
Python Program to Find ASCII Value of Character
Python Dictionary popitem()
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python Dictionary get()
Python Program to Check if a Number is Positive, Negative or 0
Python Program to Count the Number of Digits Present In a Number
Python Program to Append to a File
Deep Learning with Python - Francois Chollet
Python bool()
APIs in Node.js vs Python - A Comparison
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Python timestamp to datetime and vice-versa
Python Shallow Copy and Deep Copy
Python Tuple
Python List copy()
Python String rstrip()
Python frozenset()
Python all()
Python Program to Print Colored Text to the Terminal
Python while Loop
Python Matrices and NumPy Arrays