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 hash()
Python print()
Python List append()
Python Program to Differentiate Between type() and isinstance()
Python Program to Check the File Size
Python Directory and Files Management
Learning scikit-learn Machine Learning in Python - Raul Garreta & Guillermo Moncecchi
Python max()
Python Program to Calculate the Area of a Triangle
Python Program to Trim Whitespace From a String
Python String replace()
Python Program to Print all Prime Numbers in an Interval
Python Program to Convert Two Lists Into a Dictionary
Python String swapcase()
Python Program to Convert Kilometers to Miles
Python property()
Python Program to Find Armstrong Number in an Interval
Python complex()
Python Program to Find LCM
Python for Loop
Python Set clear()
Python Program to Find the Factors of a Number
Python Inheritance
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Python Sets
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Python ord()
Machine Learning Applications Using Python - Cases studies form Healthcare, Retail, and Finance - Pu...
Python Set symmetric_difference_update()
Python strptime()
Python Program to Check If a List is Empty
Python List remove()