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() + " ");
}
}
}
Python
# 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)
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
OutputSorted 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
Python
# 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)
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
OutputSorted 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
Java
import java.util.*;
public class Main {
public static void main(String[] args) {
// Initialize a TreeMap to store key-value pairs
TreeMap<String, String> myMap = new TreeMap<>();
// Add key-value pairs to the TreeMap
myMap.put("red", "#FF0000");
myMap.put("green", "#008000");
myMap.put("black", "#000000");
myMap.put("white", "#FFFFFF");
// Sort and print the TreeMap
System.out.println("Sorted dictionary is:");
for (Map.Entry<String, String> entry : myMap.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
}
Python
# 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])
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
// Initialize a dictionary
Dictionary<string, string> myDict = new Dictionary<string, string>()
{
{ "red", "#FF0000" },
{ "green", "#008000" },
{ "black", "#000000" },
{ "white", "#FFFFFF" }
};
// Sort dictionary by value
var sortedDict = myDict.OrderBy(pair => pair.Value);
// Print sorted dictionary
Console.WriteLine("Sorted dictionary is :");
foreach (var pair in sortedDict)
{
Console.WriteLine($"{pair.Key} {pair.Value}");
}
// 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]);
});
OutputSorted 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():
C++
#include <algorithm>
#include <iostream>
#include <map>
#include <vector>
using namespace std;
// Comparator function to sort map by value
bool sortByValue(const pair<string, int>& a,
const pair<string, int>& b)
{
return (a.second < b.second);
}
int main()
{
// Initialize a map
map<string, int> my_dict = {
{ "a", 23 }, { "g", 67 }, { "e", 12 }, { "45", 90 }
};
// Sorting dictionary
vector<pair<string, int> > sorted_dict(my_dict.begin(),
my_dict.end());
sort(sorted_dict.begin(), sorted_dict.end(),
sortByValue);
// Printing sorted dictionary
cout << "Sorted dictionary is:" << endl;
for (const auto& pair : sorted_dict) {
cout << pair.first << ": " << pair.second << endl;
}
return 0;
}
// This code is contibuted by Utkarsh.
Java
import java.util.*;
public class SortMapByValue {
// Comparator function to sort map by value
static class SortByValue
implements Comparator<Map.Entry<String, Integer> > {
public int compare(Map.Entry<String, Integer> a,
Map.Entry<String, Integer> b)
{
return a.getValue().compareTo(b.getValue());
}
}
public static void main(String[] args)
{
// Initialize a map
Map<String, Integer> myDict = new HashMap<>();
myDict.put("a", 23);
myDict.put("g", 67);
myDict.put("e", 12);
myDict.put("45", 90);
// Sorting dictionary
List<Map.Entry<String, Integer> > sortedDict
= new ArrayList<>(myDict.entrySet());
Collections.sort(sortedDict, new SortByValue());
// Printing sorted dictionary
System.out.println("Sorted dictionary is:");
System.out.print("[");
for (int i = 0; i < sortedDict.size(); i++) {
System.out.print(
"(" + sortedDict.get(i).getKey() + ", "
+ sortedDict.get(i).getValue() + ")");
if (i != sortedDict.size() - 1) {
System.out.print(", ");
}
}
System.out.println("]");
}
}
// This code is contributed by Monu.
Python
# 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)
JavaScript
// Comparator function to sort array of objects by value
function sortByValue(a, b) {
return a[1] - b[1];
}
// Initialize a map
let my_dict = new Map([
["a", 23],
["g", 67],
["e", 12],
["45", 90]
]);
// Sorting dictionary
let sorted_dict = Array.from(my_dict.entries()).sort(sortByValue);
// Printing sorted dictionary
console.log("Sorted dictionary is:");
sorted_dict.forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});
OutputSorted 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:
C++
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
int main() {
// Initialize a map
map<int, int> myDict = {{1, 2}, {3, 4}, {4, 3}, {2, 1}, {0, 0}};
// Convert the map into a vector of key-value pairs
vector<pair<int, int>> items(myDict.begin(), myDict.end());
// Sort the vector based on the values
sort(items.begin(), items.end(), [](const pair<int, int>& a, const pair<int, int>& b) {
return a.second < b.second;
});
// Initialize an empty vector of pairs to store the sorted dictionary
vector<pair<int, int>> sortedDict;
// Populate the sorted dictionary vector
for (const auto& item : items) {
sortedDict.push_back(item);
}
// Print the sorted dictionary
cout << "Sorted dictionary is:" << endl;
for (const auto& kv : sortedDict) {
cout << kv.first << ": " << kv.second << endl;
}
return 0;
}
// This code is contributed by shivamgupta0987654321
Java
import java.util.*;
public class SortDictionaryByValue {
public static LinkedHashMap<Integer, Integer>
sortDictionaryByValue(Map<Integer, Integer> myMap)
{
// Create a list of entries from the map
List<Map.Entry<Integer, Integer> > entryList
= new LinkedList<>(myMap.entrySet());
// Sort the list based on the values
entryList.sort(Map.Entry.comparingByValue());
// Create a new LinkedHashMap to maintain the
// insertion order
LinkedHashMap<Integer, Integer> sortedMap
= new LinkedHashMap<>();
// Copy sorted entries to the LinkedHashMap
for (Map.Entry<Integer, Integer> entry :
entryList) {
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
public static void main(String[] args)
{
// Initialize a dictionary
Map<Integer, Integer> myMap = new HashMap<>();
myMap.put(1, 2);
myMap.put(3, 4);
myMap.put(4, 3);
myMap.put(2, 1);
myMap.put(0, 0);
// Sort the dictionary by value
LinkedHashMap<Integer, Integer> sortedMap
= sortDictionaryByValue(myMap);
// Print the sorted dictionary
System.out.println("Sorted dictionary is :");
for (Map.Entry<Integer, Integer> entry :
sortedMap.entrySet()) {
System.out.println(entry.getKey() + ": "
+ entry.getValue());
}
}
}
Python
# 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 in the specified format
print("Sorted dictionary is:")
for key, value in sorted_dict.items():
print(f"{key}: {value}")
JavaScript
// Initialize a dictionary
const myDict = { 1: 2, 3: 4, 4: 3, 2: 1, 0: 0 };
// Convert the dictionary into an array of key-value pairs
const items = Object.keys(myDict).map(key => [parseInt(key), myDict[key]]);
// Sort the array based on the values
items.sort((a, b) => a[1] - b[1]);
// Initialize an empty string to store the sorted dictionary representation
let sortedDictString = "Sorted dictionary is:\n";
// Populate the sorted dictionary string
items.forEach(item => {
sortedDictString += `${item[0]}: ${item[1]}\n`;
});
// Print the sorted dictionary
console.log(sortedDictString);
OutputSorted 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:
C++
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
int main() {
// Initialize a map
std::map<std::string, int> myMap;
myMap["hello"] = 1;
myMap["python"] = 5;
myMap["world"] = 3;
// Sort the map by value
std::vector<std::pair<std::string, int>> sortedEntries(myMap.begin(), myMap.end());
std::sort(sortedEntries.begin(), sortedEntries.end(), [](const auto& a, const auto& b) {
return a.second < b.second;
});
// Print the sorted map
std::cout << "Sorted dictionary is:" << std::endl;
for (const auto& entry : sortedEntries) {
std::cout << entry.first << ": " << entry.second << std::endl;
}
return 0;
}
Java
import java.util.*;
public class Main {
public static void main(String[] args)
{
// Initialize a dictionary
Map<String, Integer> myMap = new HashMap<>();
myMap.put("hello", 1);
myMap.put("python", 5);
myMap.put("world", 3);
// Sort the dictionary by value
List<Map.Entry<String, Integer> > sortedEntries
= new ArrayList<>(myMap.entrySet());
Collections.sort(
sortedEntries,
Comparator.comparing(Map.Entry::getValue));
// Print the sorted dictionary
System.out.println("Sorted dictionary is:");
for (Map.Entry<String, Integer> entry :
sortedEntries) {
System.out.println(entry.getKey() + ": "
+ entry.getValue());
}
}
}
Python
# Define a dictionary
my_dict = {"hello": 1, "python": 5, "world": 3}
# Sort the dictionary by value
sorted_dict = sorted(my_dict.items(), key=lambda x: x[1])
# Print the sorted dictionary
print("Sorted dictionary is:")
for key, value in sorted_dict:
print(key + ": " + str(value))
JavaScript
// Define a dictionary
let myMap = new Map();
myMap.set("hello", 1);
myMap.set("python", 5);
myMap.set("world", 3);
// Convert the Map to an array of entries and sort it by value
let sortedEntries = Array.from(myMap.entries()).sort((a, b) => a[1] - b[1]);
// Print the sorted dictionary
console.log("Sorted dictionary is:");
sortedEntries.forEach(([key, value]) => {
console.log(key + ": " + value);
});
OutputSorted 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:
C++
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
// Initialize a dictionary
map<string, string> my_dict = {{"red", "# FF0000"}, {"green", "# 008000"},
{"black", "# 000000"}, {"white", "# FFFFFF"}};
// Create a vector of pairs to store key-value pairs
vector<pair<string, string>> dict_vec;
// Copy key-value pairs from dictionary to vector
for (auto const& pair : my_dict) {
dict_vec.push_back(pair);
}
// Sort the vector by value in reverse order
sort(dict_vec.begin(), dict_vec.end(),
[](const pair<string, string>& a, const pair<string, string>& b) {
return a.second > b.second;
});
// Print the sorted dictionary
cout << "Sorted dictionary is:" << endl;
for (const auto& pair : dict_vec) {
cout << pair.first << " " << pair.second << endl;
}
return 0;
}
Java
import java.util.*;
public class Main {
public static void main(String[] args) {
// Initialize a HashMap
HashMap<String, String> myMap = new HashMap<>();
myMap.put("red", "#FF0000");
myMap.put("green", "#008000");
myMap.put("black", "#000000");
myMap.put("white", "#FFFFFF");
// Convert HashMap to a List of Map.Entry objects
List<Map.Entry<String, String>> mapList = new ArrayList<>(myMap.entrySet());
// Sort the list by value in reverse order
Collections.sort(mapList, new Comparator<Map.Entry<String, String>>() {
@Override
public int compare(Map.Entry<String, String> a, Map.Entry<String, String> b) {
return b.getValue().compareTo(a.getValue());
}
});
// Print the sorted dictionary
System.out.println("Sorted dictionary is:");
for (Map.Entry<String, String> entry : mapList) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
}
Python
# 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])
JavaScript
// Initialize a dictionary (object in JavaScript)
let myDict = {
"red": "#FF0000",
"green": "#008000",
"black": "#000000",
"white": "#FFFFFF"
};
// Convert dictionary to an array of key-value pairs
let dictArray = Object.entries(myDict);
// Sort the array by value in reverse order
dictArray.sort((a, b) => {
return b[1].localeCompare(a[1]);
});
// Print the sorted dictionary
console.log("Sorted dictionary is:");
dictArray.forEach(pair => {
console.log(pair[0] + " " + pair[1]);
});
OutputSorted dictionary is :
white # FFFFFF
red # FF0000
green # 008000
black # 000000
Similar Reads
Different ways of sorting Dictionary by Keys and Reverse sorting by keys 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, we will discuss 10 different w
8 min read
Ways to sort list of dictionaries by values in Python â Using itemgetter In this article, we will cover how to sort a dictionary by value in Python. To sort a list of dictionaries by the value of the specific key in Python we will use the following method in this article.In everyday programming, sorting has always been a helpful tool. Python's dictionary is frequently ut
2 min read
Ways to sort list of dictionaries by values in Python - Using lambda function In this article, we will cover how to sort a dictionary by value in Python. Sorting has always been a useful utility in day-to-day programming. Dictionary in Python is widely used in many applications ranging from competitive domain to developer domain(e.g. handling JSON data). Having the knowledge
2 min read
Sort Python Dictionary by Key or Value - Python There are two elements in a Python dictionary-keys and values. You can sort the dictionary by keys, values, or both. In this article, we will discuss the methods of sorting dictionaries by key or value using Python.Sorting Dictionary By Key Using sort()In this example, we will sort the dictionary by
6 min read
Interesting Facts About Python Dictionary Python dictionaries are one of the most versatile and powerful built-in data structures in Python. They allow us to store and manage data in a key-value format, making them incredibly useful for handling a variety of tasks, from simple lookups to complex data manipulation. There are some interesting
7 min read
Python | Sort the list alphabetically in a dictionary In Python Dictionary is quite a useful data structure, which is usually used to hash a particular key with value, so that they can be retrieved efficiently. Let's see how to sort the list alphabetically in a dictionary. Sort a List Alphabetically in PythonIn Python, Sorting a List Alphabetically is
3 min read