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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads