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:
Minimum Value Keys in Dictionary - Python
Next article icon

Python - Minimum value key assignment

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

Given two dictionaries, the task is to write a Python program to assign minimum values for matching keys from both dictionaries.

Examples:

Input : test_dict1 = {"gfg" : 1, "is" : 7, "best" : 8}, test_dict2 = {"gfg" : 2, "is" : 2, "best" : 10}
Output : {"gfg" : 1, "is" : 2, "best" : 8}
Explanation : Minimum of 1 and 2 is 1, hence, gfg is assigned with 1 and so on.

Input : test_dict1 = {"gfg" : 1, "is" : 7, "best" : 12}, test_dict2 = {"gfg" : 2, "is" : 2, "best" : 10}
Output : {"gfg" : 1, "is" : 2, "best" : 10}
Explanation : Minimum of 10 and 12 is 10, hence, best is assigned with 10 and so on.

Method #1 : Using dictionary comprehension + min() + items()

In this, minimum of keys' values are extracted using min(). Dictionary comprehension is used to reconstruct the dictionary with modified values.

Python3
# Python3 code to demonstrate working of # Minimum value key assignment # Using dictionary comprehension + min() + items()  # initializing dictionaries test_dict1 = {"gfg": 1, "is": 7, "best": 8} test_dict2 = {"gfg": 2, "is": 2, "best": 10}  # printing original dictionaries print("The original dictionary 1 is : " + str(test_dict1)) print("The original dictionary 2 is : " + str(test_dict2))  # using min() to assign min values res = {key: min(val, test_dict2[key]) for key, val in test_dict1.items()}  # printing result print("The minimum value keys : " + str(res)) 

Output
The original dictionary 1 is : {'gfg': 1, 'is': 7, 'best': 8} The original dictionary 2 is : {'gfg': 2, 'is': 2, 'best': 10} The minimum value keys : {'gfg': 1, 'is': 2, 'best': 8}

Method #2 : Using dict() + min() + zip()

In this, for better comparison, zip() is used for getting values to compare, min() is used to get minimum values of keys. Then dict() is used to conversion of result to dictionary.

Python3
# Python3 code to demonstrate working of # Minimum value key assignment # Using dict() + min() + zip()  # initializing dictionaries test_dict1 = {"gfg": 1, "is": 7, "best": 8} test_dict2 = {"gfg": 2, "is": 2, "best": 10}  # printing original dictionaries print("The original dictionary 1 is : " + str(test_dict1)) print("The original dictionary 2 is : " + str(test_dict2))  # using min() to assign min values # dict() for conversion of result to dictionary res = dict([min(i, j) for i, j in zip(test_dict1.items(), test_dict2.items())])  # printing result print("The minimum value keys : " + str(res)) 

Output
The original dictionary 1 is : {'gfg': 1, 'is': 7, 'best': 8} The original dictionary 2 is : {'gfg': 2, 'is': 2, 'best': 10} The minimum value keys : {'gfg': 1, 'is': 2, 'best': 8}

Method #3: Using union

Approach

using union to find the minimum keys

Algorithm

1. Create an empty dictionary called result_dict.
2. For each key in the union of test_dict1 and test_dict2, check if it exists in both dictionaries.
3. If it exists in both dictionaries, assign the minimum value between the two dictionaries to the key in result_dict.
4. If it exists only in test_dict1, assign the value of the key in test_dict1 to result_dict.
5. If it exists only in test_dict2, assign the value of the key in test_dict2 to result_dict.
6. Return result_dict.

Python3
def minimum_value_key_assignment(test_dict1, test_dict2):     # Create an empty dictionary called `result_dict`.     result_dict = {}     # For each key in the union of `test_dict1` and `test_dict2`, check if it exists in both dictionaries.     for key in set(test_dict1.keys()) | set(test_dict2.keys()):         # If it exists in both dictionaries, assign the minimum value between the two dictionaries to the key in `result_dict`.         if key in test_dict1 and key in test_dict2:             result_dict[key] = min(test_dict1[key], test_dict2[key])         # If it exists only in `test_dict1`, assign the value of the key in `test_dict1` to `result_dict`.         elif key in test_dict1:             result_dict[key] = test_dict1[key]         # If it exists only in `test_dict2`, assign the value of the key in `test_dict2` to `result_dict`.         else:             result_dict[key] = test_dict2[key]     # Return `result_dict`.     return result_dict test_dict1 = {'gfg' : 1, 'is' : 7, 'best' : 8} test_dict2 = {'gfg' : 2, 'is' : 2, 'best' : 10} print( minimum_value_key_assignment(test_dict1, test_dict2)) 

Output
{'gfg': 1, 'best': 8, 'is': 2}

Time complexity: O(n), where n is the number of keys in both dictionaries.
Auxiliary Space: O(n), where n is the number of keys in both dictionaries.

Method 4 : using the built-in function setdefault().

 step-by-step approach:

Initialize an empty dictionary result_dict.
Loop through the keys of test_dict1 and test_dict2 using the set() function to get a set of all unique keys in both dictionaries.
For each key, use the min() function to get the minimum value between the two dictionaries using the get() method to avoid raising a KeyError if a key is missing in one of the dictionaries.
Use the setdefault() method to update result_dict with the minimum value key assignment for each key.
Return result_dict.

Python3
# Python3 code to demonstrate working of # Minimum value key assignment # Using setdefault()  # initializing dictionaries test_dict1 = {"gfg": 1, "is": 7, "best": 8} test_dict2 = {"gfg": 2, "is": 2, "best": 10}  # printing original dictionaries print("The original dictionary 1 is : " + str(test_dict1)) print("The original dictionary 2 is : " + str(test_dict2))  # using setdefault() to assign min values result_dict = {} for key in set(test_dict1.keys()) | set(test_dict2.keys()):     result_dict.setdefault(key, min(test_dict1.get(key, float('inf')), test_dict2.get(key, float('inf'))))  # printing result print("The minimum value keys : " + str(result_dict)) 

Output
The original dictionary 1 is : {'gfg': 1, 'is': 7, 'best': 8} The original dictionary 2 is : {'gfg': 2, 'is': 2, 'best': 10} The minimum value keys : {'is': 2, 'best': 8, 'gfg': 1} 

The time complexity of this approach is O(n), where n is the total number of unique keys in both dictionaries. The auxiliary space complexity is also O(n), as we create a new dictionary with all the unique keys and their minimum value assignments.


Next Article
Minimum Value Keys in Dictionary - Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python dictionary-programs
Practice Tags :
  • python

Similar Reads

  • Minimum Value Keys in Dictionary - Python
    We are given a dictionary and need to find all the keys that have the minimum value among all key-value pairs. The goal is to identify the smallest value in the dictionary and then collect every key that matches it. For example, in {'a': 3, 'b': 1, 'c': 2, 'd': 1}, the minimum value is 1, so the res
    4 min read
  • Python - Maximum value assignment in Nested Dictionary
    Sometimes, while working with Python dictionaries, we can have a problem in which we need to assign to the outer key, the item with maximum value in inner keys. This kind of problem can occur in day-day programming and web development domains. Let's discuss a way in which this task can be performed.
    3 min read
  • Python | Index minimum value Record
    In Python, we can bind structural information in the form of tuples and then can retrieve the same, and has manyfold applications. But sometimes we require the information of a tuple corresponding to a minimum value of another tuple index. This functionality has many applications such as ranking. Le
    4 min read
  • Python - Minimum in tuple list value
    Many times, while dealing with containers in any language we come across lists of tuples in different forms, tuples in themselves can have sometimes more than native datatypes and can have list as their attributes. This article talks about the minimum of list as tuple attribute. Let’s discuss certai
    5 min read
  • Python - Assign keys with Maximum element index
    Given Dictionary with value lists, the task is to write a Python program to assign each key with an index of the maximum value in the value list. Examples: Input : test_dict = {"gfg" : [5, 3, 6, 3], "is" : [1, 7, 5, 3], "best" : [9, 1, 3, 5]} Output : {'gfg': 2, 'is': 1, 'best': 0} Explanation : Max
    4 min read
  • Keys with Maximum value - Python
    In Python, dictionaries are used to store data in key-value pairs and our task is to find the key or keys that have the highest value in a dictionary. For example, in a dictionary that stores the scores of students, you might want to know which student has the highest score. Different methods to ide
    4 min read
  • Python - Minimum in each record value list
    Many times, while dealing with containers in any language we come across lists of tuples in different forms, tuples in themselves can have sometimes more than native datatypes and can have list as their attributes. This article talks about the min of list as tuple attribute. Let’s discuss certain wa
    6 min read
  • Python | Minimum element in tuple list
    Sometimes, while working with data in form of records, we can have a problem in which we need to find the minimum element of all the records received. This is a very common application that can occur in Data Science domain. Let's discuss certain ways in which this task can be performed. Method #1 :
    5 min read
  • Python - Minimum element indices
    Sometimes, while working with Python lists, we can have a problem in which we intend to find the position of minimum element of list. This task is easy and discussed many times. But sometimes, we can have multiple minimum elements and hence multiple minimum positions. Let’s discuss a shorthand to ac
    3 min read
  • Python - Minimum value pairing for dictionary keys
    Given two lists, key and value, construct a dictionary, which chooses minimum values in case of similar key value pairing. Input : test_list1 = [4, 7, 4, 8], test_list2 = [5, 7, 2, 9] Output : {8: 9, 7: 7, 4: 2} Explanation : For 4, there are 2 options, 5 and 2, 2 being smallest is paired. Input : t
    7 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