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 by value list length
Next article icon

Python - Sort Dictionary by Value Difference

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

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 problem can come in data domain. Let's discuss a way in which this problem can be solved. 

Method : Using sorted() + lambda + abs() + dictionary comprehension 
The combination of above functions can be used to solve this problem. In this, we perform the task of sorting using sorted(), lambda function is used to provide the logic and abs() function is used to compute the absolute difference. 

Python3
# Python3 code to demonstrate working of  # Sort Dictionary by Value Difference # Using sorted() + lambda + abs() + dictionary comprehension  # initializing dictionary test_dict = {'gfg' : [34, 87],               'is' : [10, 13],                'best' : [19, 27],                'for' : [10, 50],                'geeks' : [15, 45]}  # printing original dictionary print("The original dictionary is : " + str(test_dict))  # Sort Dictionary by Value Difference # Using sorted() + lambda + abs() + dictionary comprehension res = dict(sorted(test_dict.items(), key = lambda sub: abs(sub[1][0] - sub[1][1])))  # printing result  print("The sorted dictionary : " + str(res))  
Output : 

The original dictionary is : {'gfg': [34, 87], 'is': [10, 13], 'best': [19, 27], 'for': [10, 50], 'geeks': [15, 45]} The sorted dictionary : {'is': [10, 13], 'best': [19, 27], 'geeks': [15, 45], 'for': [10, 50], 'gfg': [34, 87]}

Time Complexity: O(nlogn), where n is the length of the list test_list 
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list 

Method 2 :  using the items() method

Explanation:

We define the sort_by_difference function that takes an item (key-value pair) of the dictionary and returns the absolute difference between the two values in the list.
We use the sorted function with the key parameter set to the sort_by_difference function to sort the dictionary items based on the value difference.
We convert the sorted items back to a dictionary using the dict constructor and assign it to the res variable.
We print the sorted dictionary using the print function.

Python3
# Python3 code to demonstrate working of  # Sort Dictionary by Value Difference # Using items() method and custom function for sorting  # initializing dictionary test_dict = {'gfg' : [34, 87],               'is' : [10, 13],                'best' : [19, 27],                'for' : [10, 50],                'geeks' : [15, 45]}  # printing original dictionary print("The original dictionary is : " + str(test_dict))  # custom function for sorting def sort_by_difference(item):     key, value = item     return abs(value[0] - value[1])  # Sort Dictionary by Value Difference # Using items() method and custom function for sorting res = dict(sorted(test_dict.items(), key=sort_by_difference))  # printing result print("The sorted dictionary : " + str(res)) 

Output
The original dictionary is : {'gfg': [34, 87], 'is': [10, 13], 'best': [19, 27], 'for': [10, 50], 'geeks': [15, 45]} The sorted dictionary : {'is': [10, 13], 'best': [19, 27], 'geeks': [15, 45], 'for': [10, 50], 'gfg': [34, 87]}

The time complexity of the sorting algorithm used in the sorted function is O(n log n) in the worst case, where n is the number of items in the dictionary.

 The auxiliary space used in this approach is O(n), where n is the number of items in the dictionary. 


Next Article
Python | Sort dictionary by value list length
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python dictionary-programs
  • Python-sort
Practice Tags :
  • python

Similar Reads

  • 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
  • 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
  • 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 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 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 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 key-value Summation
    Given a Dictionary, sort by summation of key and value. Input : test_dict = {3:5, 1:3, 4:6, 2:7, 8:1} Output : {1: 3, 3: 5, 2: 7, 8: 1, 4: 6} Explanation : 4 < 8 < 9 = 9 < 10 are increasing summation of keys and values. Input : test_dict = {3:5, 1:3, 4:6, 2:7} Output : {1: 3, 3: 5, 2: 7, 4:
    5 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
  • Sort Nested Dictionary by Value Python Descending
    Sorting a nested dictionary in Python based on its values is a common task, and it becomes even more versatile when you need to sort in descending order. In this article, we'll explore some different methods to achieve this using various Python functionalities. Let's dive into more ways to efficient
    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
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