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 Nested Dictionary by Multiple Values
Next article icon

Python | Sort nested dictionary by key

Last Updated : 26 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 can be performed using OrderedDict function which converts the dictionary to specific order as mentioned in its arguments manipulated by sorted function in it to sort by the value of key passed. 

Python3
# Python3 code to demonstrate # Sort nested dictionary by key # using OrderedDict() + sorted() from collections import OrderedDict from operator import getitem  # initializing dictionary test_dict = {'Nikhil' : { 'roll' : 24, 'marks' : 17},              'Akshat' : {'roll' : 54, 'marks' : 12},               'Akash' : { 'roll' : 12, 'marks' : 15}}  # printing original dict print("The original dictionary : " + str(test_dict))  # using OrderedDict() + sorted() # Sort nested dictionary by key res = OrderedDict(sorted(test_dict.items(),        key = lambda x: getitem(x[1], 'marks')))  # print result print("The sorted dictionary by marks is : " + str(res)) 
Output : 

The original dictionary : {'Nikhil': {'roll': 24, 'marks': 17}, 'Akash': {'roll': 12, 'marks': 15}, 'Akshat': {'roll': 54, 'marks': 12}} The sorted dictionary by marks is : OrderedDict([('Akshat', {'roll': 54, 'marks': 12}), ('Akash', {'roll': 12, 'marks': 15}), ('Nikhil', {'roll': 24, 'marks': 17})])

Time complexity: O(n log n), where n is the number of items in the dictionary. 
Auxiliary space: O(n), where n is the number of items in the dictionary

Method #2 : Using sorted() We can achieve the above result better if we just use the sorted function as it returns the result in a more usable format, dict and performs exactly the desired task. 

Python3
# Python3 code to demonstrate # Sort nested dictionary by key # using sorted()  # initializing dictionary test_dict = {'Nikhil' : { 'roll' : 24, 'marks' : 17},              'Akshat' : {'roll' : 54, 'marks' : 12},               'Akash' : { 'roll' : 12, 'marks' : 15}}  # printing original dict print("The original dictionary : " + str(test_dict))  # using sorted() # Sort nested dictionary by key res = sorted(test_dict.items(), key = lambda x: x[1]['marks'])  # print result print("The sorted dictionary by marks is : " + str(res)) 
Output : 

The original dictionary : {'Nikhil': {'marks': 17, 'roll': 24}, 'Akshat': {'marks': 12, 'roll': 54}, 'Akash': {'marks': 15, 'roll': 12}} The sorted dictionary by marks is : [('Akshat', {'marks': 12, 'roll': 54}), ('Akash', {'marks': 15, 'roll': 12}), ('Nikhil', {'marks': 17, 'roll': 24})]

Time complexity: O(n log n), where n is the number of items in the dictionary.
Auxiliary space: O(n), where n is the number of items in the dictionary, due to the creation of the sorted list.

Method 3: Use the itemgetter() method from the operator module. 

Step-by-step approach:

  • Import the operator module
  • Initialize the nested dictionary
  • Print the original dictionary
  • Use the sorted() function to sort the dictionary by the key
  • Print the sorted dictionary
Python3
import operator  # initializing dictionary test_dict = {'Nikhil': {'roll': 24, 'marks': 17},              'Akshat': {'roll': 54, 'marks': 12},              'Akash': {'roll': 12, 'marks': 15}}  # printing original dict print("The original dictionary : " + str(test_dict))  # using sorted() and itemgetter() # Sort nested dictionary by key res = sorted(test_dict.items(), key=lambda x: (x[1]['marks'], x[0]))  # print result print("The sorted dictionary by marks is : " + str(res)) 

Output
The original dictionary : {'Nikhil': {'roll': 24, 'marks': 17}, 'Akshat': {'roll': 54, 'marks': 12}, 'Akash': {'roll': 12, 'marks': 15}} The sorted dictionary by marks is : [('Akshat', {'roll': 54, 'marks': 12}), ('Akash', {'roll': 12, 'marks': 15}), ('Nikhil', {'roll': 24, 'marks': 17})]

Time complexity: O(n log n), where n is the number of elements in the dictionary.
Auxiliary space: O(n), where n is the number of elements in the dictionary, to store the sorted dictionary.


Next Article
Python Sort Nested Dictionary by Multiple Values
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python dictionary-programs
  • Python-sort
  • Python-nested-dictionary
Practice Tags :
  • python

Similar Reads

  • Python - Sorted Nested Keys in Dictionary
    Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract all the keys of nested dictionaries and render them in sorted order. This kind of application can occur in domains in which we work with data. Lets discuss certain ways in which this task can be perf
    4 min read
  • Sort a Nested Dictionary by Value in Python
    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
    3 min read
  • Python | Sort dictionary keys to list
    Sometimes, we wish to flatten the dictionary into list, the simple flattening is relatively easier, but when we wish to align keys and values in sorted way, i.e sorted by value, then it becomes quite a complex problem. Let's discuss certain ways in which this task can be performed. Method #1 : Using
    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}, '
    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
  • Python - Sort dictionary by Tuple Key Product
    Given dictionary with tuple keys, sort dictionary items by tuple product of keys. Input : test_dict = {(2, 3) : 3, (6, 3) : 9, (8, 4): 10, (10, 4): 12} Output : {(2, 3) : 3, (6, 3) : 9, (8, 4): 10, (10, 4): 12} Explanation : 6 < 18 < 32 < 40, key products hence retains order. Input : test_d
    5 min read
  • Three Level Nested Dictionary Python
    In Python, a dictionary is a built-in data type used to store data in key-value pairs. Defined with curly braces `{}`, each pair is separated by a colon `:`. This allows for efficient representation and easy access to data, making it a versatile tool for organizing information. What is 3 Level Neste
    4 min read
  • Python - Sort Dictionary key and values List
    Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform the sorting of it, wrt keys, but also can have a variation in which we need to perform a sort on its values list as well. Let's discuss certain way in which this task can be performed. Input : test_d
    6 min read
  • Sort a Dictionary - Python
    In Python, dictionaries store key-value pairs and are great for organizing data. While they weren’t ordered before Python 3.7, you can still sort them easily by keys or values, in ascending or descending order. Whether you’re arranging names alphabetically or sorting scores from highest to lowest, P
    5 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
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