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:
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python Set issubset()
Python type()
Python Global Keyword
Python break and continue
Python Inheritance
Python Program to Remove Punctuations From a String
Python hash()
Python Program to Convert Two Lists Into a Dictionary
Python Closures
Python Program to Check if a Number is Odd or Even
Python Program to Generate a Random Number
Python Set difference()
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Python @property decorator
Python Decorators
Python Program to Find the Square Root
Python round()
Python Program to Compute the Power of a Number
Python Program to Randomly Select an Element From the List
Python Program to Delete an Element From a Dictionary
Python Program to Add Two Matrices
Python hasattr()
Python chr()
Machine Learning Applications Using Python - Cases studies form Healthcare, Retail, and Finance - Pu...
Python Program to Differentiate Between del, remove, and pop on a List
Python String ljust()
Python String encode()
Python RegEx
Python Program to Iterate Over Dictionaries Using for Loop
Python Program to Make a Flattened List from Nested List
Python abs()