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 - Keys with shortest length lists in dictionary
Next article icon

Python program to sort Dictionary by Key Lengths

Last Updated : 02 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given Dictionary, sort by its key lengths.

Input : test_dict = {“Gfg” : 4, “is” : 1, “best” : 0, “for” : 3, “geeks” : 3} 
Output : {‘is’: 1, ‘Gfg’: 4, ‘for’: 3, ‘best’: 0, ‘geeks’: 3} 
Explanation : 2 < 3 = 3 < 4 < 5, are sorted lengths in order.

Input : test_dict = {“Gfg” : 4, “for” : 3, “geeks” : 3} 
Output : {‘Gfg’: 4, ‘for’: 3, ‘geeks’: 3} 
Explanation : 3 = 3 < 5, are sorted lengths in order. 
 

Method #1 : Using len() + sort() + dictionary comprehension + items()

In this, we perform the task of sorting using sort(), items() is used to get tuple pair from the dictionary, len() gets the keys lengths. Then dictionary comprehension performs the task of converting back to dictionary.

Python3




# Python3 code to demonstrate working of
# Sort Dictionary by Key Lengths
# Using len() + sort() + dictionary comprehension + items()
 
def get_len(key):
    return len(key[0])
 
# initializing dictionary
test_dict = {"Gfg" : 4, "is" : 1, "best" : 0, "for" : 3, "geeks" : 3}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# sorting using sort()
# external to render logic
test_dict_list = list(test_dict.items())
test_dict_list.sort(key = get_len)
 
# reordering to dictionary
res = {ele[0] : ele[1]  for ele in test_dict_list}
 
# printing result
print("The sorted dictionary : " + str(res))
 
 

Output:

The original dictionary is : {‘Gfg’: 4, ‘is’: 1, ‘best’: 0, ‘for’: 3, ‘geeks’: 3} The sorted dictionary : {‘is’: 1, ‘Gfg’: 4, ‘for’: 3, ‘best’: 0, ‘geeks’: 3}

Time complexity: O(n*logn)

Space complexity: O(1)

Method #2 : Using sorted() + lambda function + items() + dictionary comprehension

In this, we perform the task of sorting using sorted(), lambda function is used to provide the logic of getting key lengths.

Python3




# Python3 code to demonstrate working of
# Sort Dictionary by Key Lengths
# Using sorted() + lambda function + items() + dictionary comprehension
 
# initializing dictionary
test_dict = {"Gfg" : 4, "is" : 1, "best" : 0, "for" : 3, "geeks" : 3}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# sorting using sorted()
# lambda fnc. to render logic
test_dict_list = sorted(list(test_dict.items()), key = lambda key : len(key[0]))
 
# reordering to dictionary
res = {ele[0] : ele[1]  for ele in test_dict_list}
 
# printing result
print("The sorted dictionary : " + str(res))
 
 

Output:

The original dictionary is : {‘Gfg’: 4, ‘is’: 1, ‘best’: 0, ‘for’: 3, ‘geeks’: 3} The sorted dictionary : {‘is’: 1, ‘Gfg’: 4, ‘for’: 3, ‘best’: 0, ‘geeks’: 3}

Method #5: Using zip() + sorted() + dictionary constructor

First, a dictionary called test_dict is initialized with 5 key-value pairs, where each key is a string and each value is an integer.
The original dictionary is printed using the print() function and the concatenation operator + to join the string “The original dictionary is : ” and the string representation of the test_dict dictionary obtained using the str() function.
The sorted() function is used to sort the keys of the test_dict dictionary by their length in ascending order. The sorted keys are assigned to the variable sorted_keys.
The zip() function is used to create a new iterable where each element is a tuple consisting of a key from the sorted_keys list and the corresponding value from the test_dict dictionary.
The list comprehension [test_dict[key] for key in sorted_keys] is used to create a list of values corresponding to the keys in the sorted_keys list, in the order specified by sorted_keys.
The dict() function is used to create a new dictionary from the tuples generated by the zip() function. This new dictionary is assigned to the variable sorted_dict.
The sorted dictionary is printed using the print() function and the concatenation operator + to join the string “The sorted dictionary : ” and the string representation of the sorted_dict dictionary obtained using the str() function.

Python3




# initializing dictionary
test_dict = {"Gfg" : 4, "is" : 1, "best" : 0, "for" : 3, "geeks" : 3}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# sorting dictionary by key lengths using zip() and sorted()
sorted_keys = sorted(test_dict.keys(), key=len)
sorted_dict = dict(zip(sorted_keys, [test_dict[key] for key in sorted_keys]))
 
# printing result
print("The sorted dictionary : " + str(sorted_dict))
 
 
Output
The original dictionary is : {'Gfg': 4, 'is': 1, 'best': 0, 'for': 3, 'geeks': 3} The sorted dictionary : {'is': 1, 'Gfg': 4, 'for': 3, 'best': 0, 'geeks': 3}

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.



Next Article
Python - Keys with shortest length lists in dictionary
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python dictionary-programs
Practice Tags :
  • python

Similar Reads

  • 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
  • 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 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
  • Python - Keys with shortest length lists in dictionary
    Sometimes, while working with Python lists, we can have problem in which we need to return the keys which have minimum lengths of lists as values. This can have application in domains in which we work with data. Lets discuss certain ways in which this task can be performed. Method #1: Using len() +
    4 min read
  • Python program to Swap Keys and Values in Dictionary
    Dictionary is quite a useful data structure in programming that is usually used to hash a particular key with value so that they can be retrieved efficiently. Let’s discuss various ways of swapping the keys and values in Python Dictionary.  Method#1 (Does not work when there are multiple same values
    4 min read
  • Output of Python Program - Dictionary (set 25)
    Prerequisite: Dictionaries in PythonThese question sets will make you conversant with Dictionary Concepts in Python programming language.   Question 1: Which of the following is true about Python dictionaries? A. Items are accessed by their position in a dictionary. B. All the keys in a dictionary m
    4 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 List of Dictionaries by Multiple Keys - Python
    We are given a list of dictionaries where each dictionary contains various keys and our task is to sort the list by multiple keys. Sorting can be done using different methods such as using the sorted() function, a list of tuples, itemgetter() from the operator module. For example, if we have the fol
    3 min read
  • Output of Python Programs | Set 24 (Dictionary)
    Prerequisite : Python-Dictionary1. What will be the output? [GFGTABS] Python dictionary = {"geek":10, "for":45, "geeks": 90} print("geek" in dictionary) [/GFGTABS]Options: 10FalseTrueErrorOutput:3. TrueExplanation: in is used to check the key exist in dictiona
    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