Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Sort List by Dictionary values
Next article icon

Sort a Nested Dictionary by Value in Python

Last Updated : 12 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
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.


Next Article
Python - Sort List by Dictionary values
author
moneeshnagireddy
Improve
Article Tags :
  • Python
  • Python Programs
  • python-dict
Practice Tags :
  • python
  • python-dict

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
  • Python | Sort dictionary by value list length
    While working with Python, one might come to a problem in which one needs to perform a sort on dictionary list value length. This can be typically in case of scoring or any type of count algorithm. Let's discuss a method by which this task can be performed. Method 1: Using sorted() + join() + lambda
    4 min read
  • 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 efficient
    3 min read
  • Sort a List of Python Dictionaries by a Value
    Sorting a list of dictionaries by a specific value is a common task in Python programming. Whether you're dealing with data manipulation, analysis, or simply organizing information, having the ability to sort dictionaries based on a particular key is essential. In this article, we will explore diffe
    3 min read
  • Python - Sort Dictionary by Value Difference
    Sometimes, while working with Python dictionaries, we can have problem in which in which we need to perform sorting of items on basis of various factors. One such can be on basis of absolute difference of dual value list. This can occur in Python > 3.6, as dictionaries are ordered. This kind of p
    3 min read
  • Second largest value in a Python Dictionary
    In this problem, we will find the second-largest value in the given dictionary. Examples: Input : {'one':5, 'two':1, 'three':6, 'four':10} Output : Second largest value of the dictionary is 6 Input : {1: 'Geeks', 'name': 'For', 3: 'Geeks'} Output : Second largest value of the dictionary is Geeks C/C
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences