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 Dictionary List by Key's ith Index value
Next article icon

Python | Sort dictionary by value list length

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

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

The combination of above functions can be used to perform this particular task. In this, we just use the lambda function to perform this particular task, sorted and join function perform the required sorting and encapsulation of results respectively. 

Python3




# Python3 code to demonstrate working of
# Sort dictionary by value list length
# using sorted() + join() + lambda
 
# Initialize dictionary
test_dict = {'is': [1, 2], 'gfg': [3], 'best': [1, 3, 4]}
 
# Printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# using sorted() + join() + lambda
# Sort dictionary by value list length
res = ' '.join(sorted(test_dict, key=lambda key: len(test_dict[key])))
 
# Printing result
print("Sorted keys by value list : " + res)
 
 
Output : 
The original dictionary is : {'is': [1, 2], 'best': [1, 3, 4], 'gfg': [3]} Sorted keys by value list : gfg is best

Method 2: Using collections.OrderedDict()

collections.OrderedDict() can be used to perform the same task. 

Python3




# Python3 code to demonstrate working of
# Sort dictionary by value list length
# using collections.OrderedDict()
   
# Importing OrderedDict from collections
from collections import OrderedDict
   
# Initialize dictionary
test_dict = {'is': [1, 2], 'gfg': [3], 'best': [1, 3, 4]}
   
# Printing original dictionary
print("The original dictionary is : " + str(test_dict))
   
# using collections.OrderedDict()
# Sort dictionary by value list length
res = OrderedDict(sorted(test_dict.items(), key = lambda x : len(x[1]))).keys()
   
# printing result
print("Sorted keys by value list : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy
 
 
Output
The original dictionary is : {'is': [1, 2], 'gfg': [3], 'best': [1, 3, 4]} Sorted keys by value list : odict_keys(['gfg', 'is', 'best'])

Time Complexity: O(N log N)
Auxiliary Space: O(N)

Method 3: Using list comprehension + sorted() + len()

  1. Initialize the dictionary with key-value pairs as given in the problem statement.
  2. Create a list of tuples containing the key-value pairs of the dictionary using list comprehension.
  3. Sort the list of tuples based on the length of the value list using the sorted() method and the len() function.
  4. Create a new list of sorted keys by extracting the keys from the sorted list of tuples using a list comprehension.
  5. Print the original dictionary and the sorted list of keys.

Python3




# Initialize dictionary
test_dict = {'is': [1, 2], 'gfg': [3], 'best': [1, 3, 4]}
 
# Printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# using list comprehension + sorted() + len()
# Sort dictionary by value list length
res = [k for k, v in sorted(test_dict.items(), key=lambda item: len(item[1]))]
 
# printing result
print("Sorted keys by value list : " + str(res))
 
 
Output
The original dictionary is : {'is': [1, 2], 'gfg': [3], 'best': [1, 3, 4]} Sorted keys by value list : ['gfg', 'is', 'best']

Time Complexity: O(n*logn) where n is the number of items in the dictionary.
Auxiliary Space: O(n)

Method 4: Use the heapq module

Python3




import heapq
 
# Initialize dictionary
test_dict = {'is': [1, 2], 'gfg': [3], 'best': [1, 3, 4]}
 
# Create empty heap
heap = []
 
# Loop through items and append to heap
for k, v in test_dict.items():
    heapq.heappush(heap, (len(v), k))
 
# Extract smallest elements from heap and reverse the order
res = [heapq.heappop(heap)[1] for _ in range(len(heap))]
 
# Print result
print("Sorted keys by value list : " + str(res))
 
 
Output
Sorted keys by value list : ['gfg', 'is', 'best']

Time complexity: O(n log n) (where n is the number of items in the dictionary)
Auxiliary space: O(n) (to store the heap)

Method 5: Using built-in zip() function and a list comprehension:

Python3




# Python3 code to demonstrate working of
# Sort dictionary by value list length
# using zip() and list comprehension
 
# Initialize dictionary
test_dict = {'is': [1, 2], 'gfg': [3], 'best': [1, 3, 4]}
 
# Printing original dictionary
print("The original dictionary is: " + str(test_dict))
 
# using zip() and list comprehension
# Sort dictionary by value list length
res = [k for _, k in sorted(
    zip(map(len, test_dict.values()), test_dict.keys()))]
 
# Printing result
print("Sorted keys by value list: " + ' '.join(res))
 
 
Output
The original dictionary is: {'is': [1, 2], 'gfg': [3], 'best': [1, 3, 4]} Sorted keys by value list: gfg is best

Time complexity: O(n log n) (where n is the number of items in the dictionary)
Auxiliary space: O(n) (to store the heap)



Next Article
Python - Sort Dictionary List by Key's ith Index value
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python dictionary-programs
  • Python-sort
Practice Tags :
  • python

Similar Reads

  • 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 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 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
  • 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 List by Key's ith Index value
    Given List of dictionaries, sort dictionaries on basis of Key's ith index value Input : [{"Gfg" : "Best", "for" : "Geeks"}, {"Gfg" : "Good", "for" : "Me"}, {"Gfg" : "Better", "for" : "All"}], K = "Gfg", i = 1 Output : [{'Gfg': 'Best', 'for': 'Geeks'}, {'Gfg': 'Better', 'for': 'All'}, {'Gfg': 'Good',
    7 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 - Value length dictionary
    Sometimes, while working with a Python dictionary, we can have problems in which we need to map the value of the dictionary to its length. This kind of application can come in many domains including web development and day-day programming. Let us discuss certain ways in which this task can be perfor
    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
  • 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 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
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