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 Tuple count()
Python Program to Append to a File
Python Program to Check If a List is Empty
Python Program to Parse a String to a Float or Int
Python datetime
Python Program to Slice Lists
Python String splitlines()
Python Program to Merge Mails
Python String upper()
Python Program to Check If a String Is a Number (Float)
Deep Learning with Python - Francois Chollet
Python staticmethod()
Python Program to Display Powers of 2 Using Anonymous Function
Python input()
Python Program to Calculate the Area of a Triangle
Python oct()
Python Program to Illustrate Different Set Operations
Python String isdecimal()
Python hash()
Python Dictionary update()
Python Closures
Python Dictionary
Python Program to Find HCF or GCD
Python Program to Transpose a Matrix
Python Set intersection()
Python String center()
Python abs()
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
Python Errors and Built-in Exceptions
Python Program to Find the Factors of a Number
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python set()