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 Check if a Number is Odd or Even
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Deep Learning with Python - Francois Cholletf
Python Program to Create a Long Multiline String
Python String ljust()
Python Set discard()
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Python Exception Handling Using try, except and finally statement
Python Program to Get the Class Name of an Instance
Python strftime()
Python String rjust()
Python any()
Python String lstrip()
Python Program to Slice Lists
Python Statement, Indentation and Comments
Python Program to Calculate the Area of a Triangle
Python Closures
Intelligent Projects Using Python - Santanu Pattanayak
Python Set difference_update()
Python List count()
Python Program to Convert Two Lists Into a Dictionary
Python Program to Get the Full Path of the Current Working Directory
Python String isnumeric()
Python Directory and Files Management
Python eval()
Python String index()
Python globals()
Python break and continue
Python Dictionary copy()
Python isinstance()
Python Program to Add Two Numbers
Python time Module