Sort a Nested Dictionary by Value in Python
Last Updated :
12 Feb, 2024
Sorting a nested dictionary in Python involves understanding its structure, defining sorting criteria, and utilizing the `sorted()` function or `.sort()` method with a custom sorting function, often a lambda. This process is essential for organizing complex, hierarchical data efficiently. Mastery of sorting nested dictionaries enhances data manipulation capabilities, crucial for effective data analysis and algorithm development.
Sort a Nested Dictionary by Value in Python
Below are some of the ways by which we can sort a nested dictionary by value in Python:
- Using sorted() Method
- Using itemgetter() Method
- Using json.dumps() Method
- Using Recursion
Sort a Nested Dictionary Using sorted() with a Custom Sort Key
In this example, a nested dictionary `nested_dict` with keys 'a', 'b', and 'c' is sorted based on the value associated with the 'key' key within each nested dictionary using sorted() method. The result is a new dictionary `sorted_dict` with keys ordered by ascending values of the 'key' in the nested dictionaries.
Python3
nested_dict = {'a': {'key': 3}, 'b': {'key': 1}, 'c': {'key': 2}}
sorted_dict = dict(
sorted(nested_dict.items(), key=lambda item: item[1]['key']))
print(sorted_dict)
Output{'b': {'key': 1}, 'c': {'key': 2}, 'a': {'key': 3}}
Sort a Nested Dictionary by Value Using itemgetter() Method
In this example, a nested dictionary `nested_dict` with keys 'a', 'b', and 'c' is sorted based on the values associated with the 'key' key within each nested dictionary, using the itemgetter() function. The result is a new dictionary `sorted_dict` with keys ordered by ascending values of the 'key' in the nested dictionaries.
Python3
from operator import itemgetter
nested_dict = {'a': {'key': 3}, 'b': {'key': 1}, 'c': {'key': 2}}
sorted_dict = dict(
sorted(nested_dict.items(), key=lambda item: itemgetter('key')(item[1])))
print(sorted_dict)
Output{'b': {'key': 1}, 'c': {'key': 2}, 'a': {'key': 3}}
Sort a Nested Dictionary by Value Using json.dumps() Method
In this example, the nested dictionary `nested_dict` is sorted based on keys in ascending order using the json.dumps() and `json.loads` functions. Note that sorting is applied to the keys, not the values within the nested dictionaries.
Python3
import json
nested_dict = {3: {'key': 3}, 1: {'key': 1}, 2: {'key': 2}}
sorted_dict = json.loads(json.dumps(nested_dict, sort_keys=True))
print(sorted_dict)
Output{'1': {'key': 1}, '2': {'key': 2}, '3': {'key': 3}}
Sort a Nested Dictionary by Value Using Recursion
In this example, the function `sort_nested_dict` recursively sorts a nested dictionary `d` based on both keys and values. It iterates through the items of the dictionary, checking if a value is itself a dictionary. If it is, the function is called recursively to sort the inner dictionary. The result, stored in `sorted_dict`, is a dictionary with keys ordered alphabetically and values sorted recursively if they are dictionaries.
Python3
def sort_nested_dict(d):
for key, value in d.items():
if isinstance(value, dict):
d[key] = sort_nested_dict(value)
return dict(sorted(d.items(), key=lambda item: str(item[1]) if not isinstance(item[1], dict) else str(sort_nested_dict(item[1]))))
nested_dict = {'a': {'key': 3}, 'b': {'key': 1},
'c': {'key': 2, 'inner': {'z': 3, 'x': 1}}}
sorted_dict = sort_nested_dict(nested_dict)
print(sorted_dict)
Output{'b': {'key': 1}, 'c': {'key': 2, 'inner': {'x': 1, 'z': 3}}, 'a': {'key': 3}}
Conclusion
In conclusion, Sorting nested dictionaries in Python requires understanding their structure and adeptly using sorting functions. It involves discerning keys, defining sorting criteria, and utilizing the sorted() function with custom lambda functions for depth-aware comparison. Rigorous testing ensures the accuracy of the sorting process, a vital skill in data manipulation and analysis.
Similar Reads
Python Sort Nested Dictionary by Multiple Values We are given a nested dictionary and our task is to sort a nested dictionary by multiple values in Python and print the result. In this article, we will see how to sort a nested dictionary by multiple values in Python. Example: Input : {'A': {'score': 85, 'age': 25}, 'B': {'score': 92, 'age': 30}, '
3 min read
Python - Sort List by Dictionary values Sometimes while working with a Python dictionary, we can have problems in which we need to perform a sort of list according to the corresponding value in the dictionary. This can have applications in many domains, including data and web development. Let's discuss certain ways in which this task can
3 min read
Python - Sort Dictionary by Values and Keys Given a dictionary, sort according to descended values, if similar values, then by keys lexicographically. Input : test_dict = {"gfg" : 1, "is" : 1, "best" : 1, "for" : 1, "geeks" : 1} Output : {"best" : 1, "is" : 1, "for" : 1, "geeks" : 1, "gfg" : 1} Explanation : All values are equal, hence lexico
3 min read
Sort Python Dictionary by Value Python dictionaries are versatile data structures that allow you to store key-value pairs. While dictionaries maintain the order of insertion. sorting them by values can be useful in various scenarios. In this article, we'll explore five different methods to sort a Python dictionary by its values, a
3 min read
Python | Sort nested dictionary by key Sorting has quite vivid applications and sometimes, we might come up with a problem in which we need to sort the nested dictionary by the nested key. This type of application is popular in web development as JSON format is quite popular. Let's discuss certain ways in which this can be performed. Met
4 min read