What is the ValueSortedDict() method in Python?

Overview

A dictionary in Python is an unsorted key-value pair data structure, where key-value pairs are comma-separated. It is useful for faster lookups.

This dictionary can be sorted based on the values using the ValueSortedDict method provided by the sortedcollections module.

Syntax

ValueSortedDict(key value pairs)

Parameters

This method takes a dictionary as a parameter.

Return value

This method returns a sorted dictionary.

Example

In the following example, we will try to sort the students dictionary according to the students' ages.

from sortedcollections import ValueSortedDict
#unsorted dict
students = {"John":11, "Vicky": 10, "Riya":13, "Elina":9}
#sort dict based on values
print(ValueSortedDict(students))

Explanation

  • Line 1: We import the ValueSortedDict method from the sortedcollections module.
  • Line 4: We declare and initialize the unsorted dictionary, students, which contains the student's name and their age as key-value pairs.
  • Line 7: We sort the students dictionary with the ValueSortedDict method. Next, we print the returned sorted dictionary.

Free Resources