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 Create Pyramid Patterns
Python Package
Python String isdigit()
Python sleep()
Python Keywords and Identifiers
Learning scikit-learn Machine Learning in Python - Raul Garreta & Guillermo Moncecchi
Python Modules
Python hash()
Python setattr()
Python Program to Append to a File
Python complex()
Python Functions
Python Program to Make a Flattened List from Nested List
Python bytearray()
Python Program to Check if a Number is Positive, Negative or 0
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python String index()
Python __import__()
Python List pop()
Python Program to Calculate the Area of a Triangle
Python Program to Check Whether a String is Palindrome or Not
Python Program to Add Two Matrices
Python Set issubset()
Python Errors and Built-in Exceptions
Python Dictionary items()
Python sum()
Python Dictionary setdefault()
Python String isdecimal()
Python Program to Measure the Elapsed Time in Python
Python Program to Display Fibonacci Sequence Using Recursion
Python Program Read a File Line by Line Into a List
Python Program to Check If Two Strings are Anagram