Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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 Dictionary key and values List
Next article icon

Python - Sort Dictionary key and values List

Last Updated : 27 Jul, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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_dict = {'c': [3], 'b': [12, 10], 'a': [19, 4]} 
Output : {'a': [4, 19], 'b': [10, 12], 'c': [3]} 

Input : test_dict = {'c': [10, 34, 3]} 
Output : {'c': [3, 10, 34]}

Sort Dictionary key and values List Using sorted() + loop

The combination of above functions can be used to solve this problem. In this, we initially sort all the values of keys, and then perform the keys sorting after that, in brute manner. 

Python3
# Python3 code to demonstrate working of  # Sort Dictionary key and values List # Using loop + dictionary comprehension  # initializing dictionary test_dict = {'gfg': [7, 6, 3],               'is': [2, 10, 3],               'best': [19, 4]}  # printing original dictionary print("The original dictionary is : " + str(test_dict))  # Sort Dictionary key and values List # Using loop + dictionary comprehension res = dict() for key in sorted(test_dict):     res[key] = sorted(test_dict[key])  # printing result  print("The sorted dictionary : " + str(res))  

Output : 

The original dictionary is : {'gfg': [7, 6, 3], 'is': [2, 10, 3], 'best': [19, 4]} The sorted dictionary : {'best': [4, 19], 'gfg': [3, 6, 7], 'is': [2, 3, 10]}

Time Complexity: O(nlogn)
Auxiliary Space: O(n)

Sort Dictionary key and values List Using dictionary comprehension + sorted()

The combination of above functions can be used to solve this problem. In this, we perform the task of dual sorting inside dictionary comprehension construct. 

Python3
# Python3 code to demonstrate working of  # Sort Dictionary key and values List # Using dictionary comprehension + sorted()  # initializing dictionary test_dict = {'gfg': [7, 6, 3],               'is': [2, 10, 3],               'best': [19, 4]}  # printing original dictionary print("The original dictionary is : " + str(test_dict))  # Sort Dictionary key and values List # Using dictionary comprehension + sorted() res = {key : sorted(test_dict[key]) for key in sorted(test_dict)}  # printing result  print("The sorted dictionary : " + str(res))  

Output : 

The original dictionary is : {'gfg': [7, 6, 3], 'is': [2, 10, 3], 'best': [19, 4]} The sorted dictionary : {'best': [4, 19], 'gfg': [3, 6, 7], 'is': [2, 3, 10]}

Time complexity: O(n log n), where n is the total number of values in the input dictionary test_dict. 
Auxiliary space: O(n), where n is the total number of values in the input dictionary test_dict. 

Sort Dictionary key and values List Using lambda function with sorted()

Sorts a dictionary by its keys and also sorts the values for each key using the sorted() function with a lambda function as the key. initializes a dictionary with some key-value pairs, sorts it, and then prints both the original and sorted dictionaries.

Python3
# Python3 code to demonstrate working of  # Sort Dictionary key and values List # Using lambda function with sorted()  # initializing dictionary test_dict = {'gfg': [7, 6, 3],               'is': [2, 10, 3],               'best': [19, 4]}  # printing original dictionary print("The original dictionary is: " + str(test_dict))  # Sort Dictionary key and values List # Using lambda function with sorted() res = dict(sorted(test_dict.items(), key=lambda x: x[0]))  for key in res:     res[key] = sorted(res[key])  # printing result  print("The sorted dictionary: " + str(res)) 

Output
The original dictionary is: {'gfg': [7, 6, 3], 'is': [2, 10, 3], 'best': [19, 4]} The sorted dictionary: {'best': [4, 19], 'gfg': [3, 6, 7], 'is': [2, 3, 10]} 

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

Sort Dictionary key and values List Using the zip() function with sorted() function.

Step-by-step approach:

  • Initialize the dictionary.
  • Get the list of keys and values separately.
  • Use the zip() function to create a list of tuples, where each tuple contains a key and its corresponding value list.
  • Sort the list of tuples using the sorted() function and a lambda function that sorts the tuples based on the first element of each tuple (i.e., the key).
  • Use a dictionary comprehension to create a new dictionary from the sorted list of tuples.
  • Print the sorted dictionary.

Below is the implementation of the above approach:

Python3
# Python3 code to demonstrate working of  # Sort Dictionary key and values List # Using zip() function with sorted()  # initializing dictionary test_dict = {'gfg': [7, 6, 3],               'is': [2, 10, 3],               'best': [19, 4]}  # printing original dictionary print("The original dictionary is: " + str(test_dict))  # Sort Dictionary key and values List # Using zip() function with sorted() keys = list(test_dict.keys()) values = list(test_dict.values()) sorted_tuples = sorted(zip(keys, values), key=lambda x: x[0]) res = {k: sorted(v) for k, v in sorted_tuples}  # printing result  print("The sorted dictionary: " + str(res)) 

Output
The original dictionary is: {'gfg': [7, 6, 3], 'is': [2, 10, 3], 'best': [19, 4]} The sorted dictionary: {'best': [4, 19], 'gfg': [3, 6, 7], 'is': [2, 3, 10]} 

Time complexity: O(n log n) due to sorting, where n is the number of keys in the dictionary.
Auxiliary space: O(n) because we are using additional space to store the list of tuples.

Sort Dictionary key and values List Using Recursive method.

Algorithm:

  1. Base Case: If the input dictionary is empty, return an empty dictionary.
  2. Recursive Case: Find the key with the minimum value list length in the input dictionary. Call it min_key.
  3. Sort the value list associated with min_key.
  4. Remove min_key from the input dictionary and call the resulting dictionary rest_dict.
  5. Recursively call sort_dict_recursive on rest_dict and call the resulting dictionary sorted_rest_dict.
  6. Return a new dictionary with min_key as the key and the sorted value list as the value, merged with sorted_rest_dict.
Python3
def sort_dict_recursive(test_dict):     if not test_dict:         return {}     min_key = min(test_dict.keys())     sorted_values = sorted(test_dict[min_key])     rest_dict = {k: v for k, v in test_dict.items() if k != min_key}     sorted_rest_dict = sort_dict_recursive(rest_dict)     return {min_key: sorted_values, **sorted_rest_dict}  test_dict = {'gfg': [7, 6, 3], 'is': [2, 10, 3], 'best': [19, 4]} res = sort_dict_recursive(test_dict) print("The original dictionary is: " + str(test_dict)) print("The sorted dictionary : " + str(res)) 

Output
The original dictionary is: {'gfg': [7, 6, 3], 'is': [2, 10, 3], 'best': [19, 4]} The sorted dictionary : {'best': [4, 19], 'gfg': [3, 6, 7], 'is': [2, 3, 10]} 

Time Complexity: O(n log n) - The function makes n recursive calls, and each call sorts a list of length m, where m is the length of the smallest values list in the remaining dictionary. Sorting a list has a time complexity of O(m log m), so the overall time complexity is dominated by the sorting operations, which gives us O(n log n).
Auxiliary Space: O(n) - The recursive function creates a new dictionary and list for each recursive call, so the space complexity is proportional to the size of the input dictionary. In the worst case, where all values lists are of equal length, the size of the output dictionary is the same as the size of the input dictionary, so the space complexity is O(n).


Next Article
Python - Sort Dictionary key and values List

M

manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python dictionary-programs
Practice Tags :
  • python

Similar Reads

    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 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 Print Dictionary Keys and Values
    When working with dictionaries, it's essential to be able to print their keys and values for better understanding and debugging. In this article, we'll explore different methods to Print Dictionary Keys and Values.Example: Using print() MethodPythonmy_dict = {'a': 1, 'b': 2, 'c': 3} print("Keys:", l
    2 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
    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
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