Open In App

Different ways of sorting Dictionary by Values and Reverse sorting by values

Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite: Dictionaries in Python

A dictionary is a collection which is unordered, changeable, and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, 10 different ways of sorting the Python dictionary by values and also reverse sorting by values are discussed.

Using lambda function along with items() and sorted(): The lambda function returns the key(0th element) for a specific item tuple, When these are passed to the sorted() method, it returns a sorted sequence which is then type-casted into a dictionary. keys() method returns a view object that displays a list of all the keys in the dictionary. sorted() is used to sort the keys of the dictionary.

Examples:

Input: my_dict = {2: ‘three’, 1: ‘two’} 
Output: [(2, ‘three’), (1, ‘two’)] 

Below is the implementation using lambda function:

C++




#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
 
int main() {
    // Initialize a map (equivalent to HashMap in Java)
    std::map<int, std::string> myMap;
    myMap[2] = "three";
    myMap[1] = "two";
 
    // Sort the map by value
    std::vector<std::pair<int, std::string>> sortedVector(myMap.begin(), myMap.end());
    // Use a lambda function for sorting based on the string values
    std::sort(sortedVector.begin(), sortedVector.end(),
        [](const std::pair<int, std::string>& kv1, const std::pair<int, std::string>& kv2) {
            return kv1.second < kv2.second;
        });
 
    // Print the sorted dictionary (map)
    std::cout << "Sorted dictionary is: [";
    for (size_t i = 0; i < sortedVector.size(); i++) {
        std::cout << "(" << sortedVector[i].first << ", '" << sortedVector[i].second << "')";
        if (i < sortedVector.size() - 1) {
            std::cout << ", ";
        }
    }
    std::cout << "]" << std::endl;
 
    return 0;
}


Java




// Java program to sort dictionary by value using lambda function
 
import java.util.*;
 
class Main {
public static void main(String[] args) {
// Initialize a HashMap
HashMap<Integer, String> myMap = new HashMap<Integer, String>();
myMap.put(2, "three");
myMap.put(1, "two");
    // Sort the HashMap by value
    List<Map.Entry<Integer, String>> sortedList = new ArrayList<Map.Entry<Integer, String>>(myMap.entrySet());
    Collections.sort(sortedList, (kv1, kv2) -> kv1.getValue().compareTo(kv2.getValue()));
 
    // Print sorted dictionary
    System.out.print("Sorted dictionary is : ");
    for (Map.Entry<Integer, String> entry : sortedList) {
        System.out.print(entry.getKey() + ":" + entry.getValue() + " ");
    }
}
}


C#




using System;
using System.Collections.Generic;
using System.Linq;
 
class Program
{
    static void Main(string[] args)
    {
        // Initialize a Dictionary
        Dictionary<int, string> myDictionary = new Dictionary<int, string>();
        myDictionary.Add(2, "three");
        myDictionary.Add(1, "two");
 
        // Sort the Dictionary by value
        var sortedList = myDictionary.OrderBy(kv => kv.Value).ToList();
 
        // Print sorted dictionary in the requested format
        Console.Write("Sorted dictionary is : [");
        for (int i = 0; i < sortedList.Count; i++)
        {
            var entry = sortedList[i];
            Console.Write($"({entry.Key}, '{entry.Value}')");
            if (i < sortedList.Count - 1)
                Console.Write(", ");
        }
        Console.WriteLine("]");
    }
}


Javascript




// Javascript program for the above approach
 
// Initialize a dictionary
let my_dict = {2: 'three', 1: 'two'};
 
// Sort the dictionary by value using lambda function
let sorted_dict = Object.entries(my_dict).sort((a, b) => a[1].localeCompare(b[1]));
 
// Print sorted dictionary
console.log("Sorted dictionary is :", sorted_dict);
 
 
// This code is contributed by rishab


Python3




# Python program to sort dictionary
# by value using lambda function
 
# Initialize a dictionary
my_dict = {2: 'three',
           1: 'two'}
 
# Sort the dictionary
sorted_dict = sorted(
  my_dict.items(),
  key = lambda kv: kv[1])
 
# Print sorted dictionary
print("Sorted dictionary is :",
      sorted_dict)


Output

Sorted dictionary is : [(2, 'three'), (1, 'two')]











The time complexity of this program is O(n log n), where n is the size of the dictionary. 

The space complexity is O(n), where n is the size of the dictionary.

Using items() alone: The method items() is used alone with two variables i.e., key and value to sort the dictionary by value.

Examples:

Input: my_dict = {‘c’: 3, ‘a’: 1, ‘d’: 4, ‘b’: 2}
Output: [(1, ‘a’), (2, ‘b’), (3, ‘c’), (4, ‘d’)] 
 

Below is the implementation using method items():

C++




#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
 
int main() {
    // Initialize a dictionary
    std::map<char, int> my_dict = {
        {'c', 3},
        {'a', 1},
        {'d', 4},
        {'b', 2}
    };
 
    // Sorting dictionary
    std::vector<std::pair<int, char>> sorted_dict;
    for (const auto& pair : my_dict) {
        sorted_dict.emplace_back(pair.second, pair.first);
    }
    std::sort(sorted_dict.begin(), sorted_dict.end());
 
    // Print sorted dictionary
    std::cout << "Sorted dictionary is :" << std::endl;
    for (const auto& pair : sorted_dict) {
        std::cout << '(' << pair.first << ", " << pair.second << ") ";
    }
    std::cout << std::endl;
 
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
 
class GFG {
    public static void main(String[] args)
    {
        // Initialize a dictionary
        TreeMap<Character, Integer> my_dict
            = new TreeMap<>();
        my_dict.put('c', 3);
        my_dict.put('a', 1);
        my_dict.put('d', 4);
        my_dict.put('b', 2);
 
        // Sorting dictionary
        List<Map.Entry<Character, Integer> > sorted_dict
            = new ArrayList<>(my_dict.entrySet());
        Collections.sort(
            sorted_dict,
            Comparator.comparing(Map.Entry::getValue));
 
        // Print sorted dictionary
        System.out.println("Sorted dictionary is :");
        for (Map.Entry<Character, Integer> entry :
             sorted_dict) {
            System.out.print("(" + entry.getValue() + ", "
                             + entry.getKey() + ") ");
        }
        System.out.println();
    }
}
 
// This code is contributed by Susobhan Akhuli


C#




using System;
using System.Collections.Generic;
using System.Linq;
 
class Program
{
    static void Main()
    {
        // Initialize a dictionary
        Dictionary<char, int> myDict = new Dictionary<char, int>
        {
            {'c', 3},
            {'a', 1},
            {'d', 4},
            {'b', 2}
        };
 
        // Sorting dictionary
        List<KeyValuePair<int, char>> sortedDict = myDict
            .Select(pair => new KeyValuePair<int, char>(pair.Value, pair.Key))
            .OrderBy(pair => pair.Key)
            .ToList();
 
        // Print sorted dictionary
        Console.WriteLine("Sorted dictionary is :");
        foreach (var pair in sortedDict)
        {
            Console.Write("(" + pair.Key + ", " + pair.Value + ") ");
        }
        Console.WriteLine();
    }
}


Javascript




// Initialize a dictionary
const my_dict = {
'c': 3,
'a': 1,
'd': 4,
'b': 2
};
 
// Sorting dictionary
const sorted_dict = Object.entries(my_dict)
.sort((a, b) => a[1] - b[1])
.map(entry => [entry[1], entry[0]]);
 
// Print sorted dictionary
console.log("Sorted dictionary is :");
console.log(sorted_dict);
 
// This code is contributed by Prince Kumar


Python3




# Python program to sort dictionary
# by value using item function
 
# Initialize a dictionary
my_dict = {'c': 3,
        'a': 1,
        'd': 4,
        'b': 2}
 
# Sorting dictionary
sorted_dict = sorted([(value, key)
for (key, value) in my_dict.items()])
 
# Print sorted dictionary
print("Sorted dictionary is :")
print(sorted_dict)


Output

Sorted dictionary is :
(1, a) (2, b) (3, c) (4, d) 





Time Complexity: O(n log n)
Space Complexity: O(n)

Using sorted() and get(): The method get() returns the value for the given key, if present in the dictionary. If not, then it will return None.

Examples:

Input: my_dict = {‘red’:’#FF0000′, ‘green’:’#008000′, ‘black’:’#000000′, ‘white’:’#FFFFFF’} 
Output: 
black #000000 
green #008000 
red #FF0000 
white #FFFFFF  

Below is the implementation using sorted() and get() method:

C++




// CPP program for the above approach
#include <algorithm>
#include <iostream>
#include <map>
#include <vector>
using namespace std;
 
int main()
{
    // Initialize a dictionary
    map<string, string> my_dict
        = { { "red", "#FF0000" },
            { "green", "#008000" },
            { "black", "#000000" },
            { "white", "#FFFFFF" } };
 
    // Sort dictionary by value
    vector<pair<string, string> > sorted_dict;
    for (const auto& pair : my_dict) {
        sorted_dict.push_back(pair);
    }
    sort(sorted_dict.begin(), sorted_dict.end(),
         [](const auto& a, const auto& b) {
             return a.second < b.second;
         });
 
    // Print sorted dictionary
    cout << "Sorted dictionary is :\n";
    for (const auto& pair : sorted_dict) {
        cout << pair.first << " " << pair.second << "\n";
    }
 
    return 0;
}
 
// This code is contributed by Susobhan Akhuli


Javascript




// Initialize an object (dictionary)
const myDict = {
    'red': '#FF0000',
    'green': '#008000',
    'black': '#000000',
    'white': '#FFFFFF'
};
 
// Sort and print the dictionary
console.log('Sorted dictionary is:');
Object.keys(myDict)
    .sort((a, b) => myDict[a].localeCompare(myDict[b]))
    .forEach(key => {
        console.log(key, myDict[key]);
    });


Python3




# Python program to sort dictionary
# by value using sorted() and get()
 
# Initialize a dictionary
my_dict = {'red': '# FF0000', 'green': '# 008000',
           'black': '# 000000', 'white': '# FFFFFF'}
 
# Sort and print dictionary
print("Sorted dictionary is :")
for w in sorted(my_dict, key = my_dict.get):
    print(w, my_dict[w])


Output

Sorted dictionary is :
black # 000000
green # 008000
red # FF0000
white # FFFFFF











Time complexity: O(nlogn) – sorting the dictionary using the sorted() function takes nlogn time, 

Auxiliary space: O(n) – creating a new list of keys in sorted order takes O(n) space.

Using itemgetter from operator:

The method itemgetter(n) constructs a callable that assumes an iterable object as input, and fetches the n-th element out of it.

Examples

Input: 
my_dict = {‘a’: 23, ‘g’: 67, ‘e’: 12, 45: 90} 
Output: 
[(‘e’, 12), (‘a’, 23), (‘g’, 67), (45, 90)] 
 

Below is the python program to sort the dictionary using itemgetter(): 

Python3




# Python program to sort dictionary
# by value using itemgetter() function
 
# Importing OrderedDict
import operator
 
# Initialize a dictionary
my_dict = {'a': 23,
           'g': 67,
           'e': 12,
           45: 90}
 
# Sorting dictionary
sorted_dict = sorted(my_dict.items(), \
             key = operator.itemgetter(1))
 
# Printing sorted dictionary
print("Sorted dictionary is :")
print(sorted_dict)


Output

Sorted dictionary is :
[('e', 12), ('a', 23), ('g', 67), (45, 90)]











Time complexity: O(n log n)

The time complexity of sorting a dictionary using the itemgetter() function is O(n log n). This is because the itemgetter() function must traverse through the dictionary and compare each element to determine the sorting order. Since comparing each element is an O(n) operation, and sorting is an O(log n) operation, the overall time complexity is O(n log n).

Space complexity: O(n)

The space complexity of sorting a dictionary using the itemgetter() function is O(n). This is because the itemgetter() function must create a new list containing all of the elements of the dictionary, which requires O(n) space.

Using OrderedDict from collections: The OrderedDict is a standard library class, which is located in the collections module. OrderedDict maintains the orders of keys as inserted.

Examples:

Input: my_dict = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} 
Output: [(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
 

Below is the implementation using Ordered Dict:

Python3




# Python program to sort dictionary
# by value using OrderedDict
 
# Import OrderedDict
from collections import OrderedDict
 
# Initialize a dictionary
my_dict = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
 
# Sort dictionary
sorted_dict = OrderedDict(sorted(\
  my_dict.items(), key = lambda x: x[1]))
 
# Print the sorted dictionary
print("Sorted dictionary is :")
print(sorted_dict)


Output

Sorted dictionary is :
OrderedDict([(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)])











Time complexity: The time complexity of this program is O(n log n), where n is the size of the dictionary.

Space complexity: The space complexity of this program is O(n), where n is the size of the dictionary.

Using Counter from collections: The counter is an unordered collection where elements are stored as Dict keys and their count as dict value. Counter elements count can be positive, zero or negative integers.

Examples: 

Input: my_dict = {‘hello’: 1, ‘python’: 5, ‘world’: 3}
Output: [(‘hello’, 1), (‘world’, 3), (‘python’, 5)] 
 

Below is the implementation using Counter from collections:

Python3




# Python program to sort dictionary
# by value using OrderedDict
 
# Import Counter
from collections import Counter
 
# Initialize a dictionary
my_dict = {'hello': 1, 'python': 5, 'world': 3}
 
# Sort and print the dictionary
sorted_dict = Counter(my_dict)
print("Sorted dictionary is :")
print(sorted_dict.most_common()[::-1])


Output

Sorted dictionary is :
[('hello', 1), ('world', 3), ('python', 5)]











Reverse Sorting Dictionary by values: The same syntax for both ascending and descending ordered sorting. For reverse sorting, the idea is to use reverse = true. with the function sorted().

Examples:

Input: 
my_dict = {‘red’:’#FF0000′, 
‘green’:’#008000′, 
‘black’:’#000000′, 
‘white’:’#FFFFFF’} 
Output: 
black #000000 
green #008000 
red #FF0000 
white #FFFFFF 
 

Below is the implementation using Reverse Sorting Dictionary by values:

Python3




# Python program to sort dictionary
# by value using sorted setting
# reverse parameter to true
 
# Initialize a dictionary
my_dict = {'red': '# FF0000', 'green': '# 008000',
           'black': '# 000000', 'white': '# FFFFFF'}
 
# Sort and print the dictionary
print("Sorted dictionary is :")
for w in sorted(my_dict, key = my_dict.get, \
                reverse = True):
    print(w, my_dict[w])


Output

Sorted dictionary is :
white # FFFFFF
red # FF0000
green # 008000
black # 000000













Last Updated : 09 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads