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 Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Python Get Current time
Python if...else Statement
Python String casefold()
Python String isdecimal()
Python Set issuperset()
Python iter()
Python Program to Append to a File
Python Program to Convert String to Datetime
Python compile()
Python Type Conversion and Type Casting
Python String rindex()
Python pass statement
Python Machine Learning - Sebastian Raschka
Python bool()
Python Program to Swap Two Variables
Python Program to Convert Decimal to Binary Using Recursion
Python List reverse()
Python File I/O Operation
Python Program to Find the Factorial of a Number
APIs in Node.js vs Python - A Comparison
Python Object Oriented Programming
Python Program to Merge Mails
Introduction to Machine Learning with Python - Andreas C.Muller & Sarah Guido
Machine Learning Applications Using Python - Cases studies form Healthcare, Retail, and Finance - Pu...
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda
Python tuple()
Python reversed()
Python sorted()
Python Program to Solve Quadratic Equation
How to Get Started With Python?
Python Program to Count the Number of Digits Present In a Number