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

Sorting Python Dictionary With Lists as Values

Last Updated : 26 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Python offers various methods to sort a dictionary with Lists as Values. This is a common task when dealing with data where you need to order elements based on different criteria. In this article, we will sort a dictionary with lists as values in Python.

Sort a Dictionary with Lists as Values in Python

Below, are the ways to Sort a Dictionary Python With Lists As Values according to different sorting criteria.

  • Using Sorted and Lambda Function
  • Using Itemgetter from Operator Module
  • Using List Comprehension and Sorted
  • Using Dictionary Comprehension and Sorted

Sort a Dictionary with Lists Using Sorted and Lambda Function

In this approach, we use the sorted() function to sort the dictionary items based on a key function. The key function (lambda x: sum(x[1])) calculates the sum of the values in the list for each dictionary item. and after that, the resulting sorted items are converted back into a dictionary.

Python3
# Sample Dictionary data = {'apple': [3, 7, 1], 'banana': [2, 5, 4], 'orange': [6, 9, 8]}  # Sorting based on the sum of the list values sorted_data = dict(sorted(data.items(), key=lambda x: sum(x[1])))  # Displaying the sorted dictionary print("Using Sorted and Lambda Function") print(sorted_data) 

Output
Using Sorted and Lambda Function {'apple': [3, 7, 1], 'banana': [2, 5, 4], 'orange': [6, 9, 8]}

Sort a Dictionary with Lists Using Itemgetter from Operator Module

In this approach we use the itemgetter function from the operator module to specify the index (in this case, 1) of the element to use for sorting.

Python3
from operator import itemgetter  # Sample Dictionary data = {'apple': [3, 7, 1], 'banana': [2, 5, 4], 'orange': [6, 9, 8]}  # Sorting based on the second element of the list sorted_data = dict(sorted(data.items(), key=itemgetter(1)))  # Displaying the sorted dictionary print("Using Itemgetter from Operator Module") print(sorted_data) 

Output
Using Itemgetter from Operator Module {'banana': [2, 5, 4], 'apple': [3, 7, 1], 'orange': [6, 9, 8]}

Sort a Dictionary with Lists Using List Comprehension and Sorted

In this approach, we used a lambda function to specify the criteria for sorting. In this case, the maximum value in the list.

Python3
# Sample Dictionary data = {'apple': [3, 7, 1], 'banana': [2, 5, 4], 'orange': [6, 9, 8]}  # Sorting based on the maximum value in the list sorted_data = dict(sorted(data.items(), key=lambda x: max(x[1])))  # Displaying the sorted dictionary print("Using List Comprehension and Sorted") print(sorted_data) 

Output
Using List Comprehension and Sorted {'banana': [2, 5, 4], 'apple': [3, 7, 1], 'orange': [6, 9, 8]}

Sort a Dictionary with Lists Using Dictionary Comprehension and Sorted

In this approach, we used a dictionary comprehension to construct a new dictionary based on the sorted items.

Python3
# Sample Dictionary data = {'apple': [3, 7, 1], 'banana': [2, 5, 4], 'orange': [6, 9, 8]}  # Sorting based on the minimum value in the list sorted_data = {k: v for k, v in sorted(data.items(), key=lambda x: min(x[1]))}  # Displaying the sorted dictionary print("Using Dictionary Comprehension and Sorted") print(sorted_data) 

Output
Using Dictionary Comprehension and Sorted {'apple': [3, 7, 1], 'banana': [2, 5, 4], 'orange': [6, 9, 8]}

Next Article
Python - Sort List by Dictionary values

A

abhay94517
Improve
Article Tags :
  • Python Programs

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
  • Python - Create a Dictionary using List with None Values
    The task of creating a dictionary from a list of keys in Python involves transforming a list of elements into a dictionary where each element becomes a key. Each key is typically assigned a default value, such as None, which can be updated later. For example, if we have a list like ["A", "B", "C"],
    3 min read
  • Python - Dictionary with Index as Value
    We are having a list we need to find index of each element and store it in form of dictionary. For example, a = ['a', 'b', 'c', 'd'] we need to find index of each elements in list so that output should be {'a': 0, 'b': 1, 'c': 2, 'd': 3}. Using Dictionary ComprehensionWe can use dictionary comprehen
    2 min read
  • Get Python Dictionary Values as List - Python
    We are given a dictionary where the values are lists and our task is to retrieve all the values as a single flattened list. For example, given the dictionary: d = {"a": [1, 2], "b": [3, 4], "c": [5]} the expected output is: [1, 2, 3, 4, 5] Using itertools.chain()itertools.chain() function efficientl
    2 min read
  • Python - Sorting a dictionary of tuples
    This task becomes particularly useful when working with structured data, where tuples represent grouped information (e.g., names and scores, items and prices). Sorting such data enhances its readability and usability for further analysis. For example, consider a dictionary d = {'student3': ('bhanu',
    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 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 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 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
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