Open In App

Sort a Nested Dictionary by Value in Python

Last Updated : 12 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

Sort Nested Dictionary by Value Python Descending
Sorting a nested dictionary in Python based on its values is a common task, and it becomes even more versatile when you need to sort in descending order. In this article, we'll explore some different methods to achieve this using various Python functionalities. Let's dive into more ways to efficiently sort nested dictionaries and gain a deeper unde
3 min read
Python | Convert flattened dictionary into nested dictionary
Given a flattened dictionary, the task is to convert that dictionary into a nested dictionary where keys are needed to be split at '_' considering where nested dictionary will be started. Method #1: Using Naive Approach Step-by-step approach : Define a function named insert that takes two parameters, a dictionary (dct) and a list (lst). This functi
8 min read
Python | Convert nested dictionary into flattened dictionary
Given a nested dictionary, the task is to convert this dictionary into a flattened dictionary where the key is separated by '_' in case of the nested key to be started. Method #1: Using Naive Approach Step-by-step approach : The function checks if the input dd is a dictionary. If it is, then it iterates over each key-value pair in the dictionary, a
8 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. Method #1 : Using OrderedDict() + sorted() This task
4 min read
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}, 'C': {'score': 78, 'age': 22}}Output: {'C': {'score
3 min read
Python - Maximum Value in Nested Dictionary
Sometimes, while working with python dictionary, we can have problem in which each key in itself is a record with several keys and we desire to substitute the value as maximum value of keys of dictionary. This kind of problem can have application in many domains that involves data. Lets discuss certain ways in which this task can be performed. Meth
4 min read
Python - Inner Nested Value List Mean in Dictionary
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to extract the mean of nested value lists in dictionary. This problem can have application in many domains including web development and competitive programming. Lets discuss certain ways in which this task can be performed. Method #1 : Using mean() + loop The
5 min read
Python - Maximum value assignment in Nested Dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to assign to the outer key, the item with maximum value in inner keys. This kind of problem can occur in day-day programming and web development domains. Let's discuss a way in which this task can be performed. Input : test_dict = {'Manjeet': {'English': 19, '
3 min read
Add a Key-Value Pair to a Nested Dictionary in Python
Dictionaries in Python are versatile data structures that allow you to store and manipulate key-value pairs. When dealing with nested dictionaries, adding a key-value pair becomes a bit more intricate. In this article, we will explore four simple methods to add a key-value pair to a nested dictionary in Python. To illustrate these methods, we will
3 min read
Python - Sort Nested keys by Value
Sometimes, while working with data records, we can have a problem in which we need to perform the sorting of nested keys of dictionary by the value of occurrence. This can have applications in arranging scores, prices etc. Lets discuss a way in which this task can be performed. Method #1 : Using sorted() + lambda + generator expression The combinat
3 min read
Practice Tags :