Python - Minimum value pairing for dictionary keys
Last Updated :
18 May, 2023
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 : test_list1 = [4, 4, 4, 4], test_list2 = [3, 7, 2, 1]
Output : {4: 1}
Explanation : All elements are for 4, smallest being 1.
Method #1 : dict() + sorted() + zip() + lambda
The combination of above functions can be used to solve this problem. In this, we perform sorting using sorted(), zip() is used to map keys with values. The dict() is used to convert result back into dictionary.
Python3
# Python3 code to demonstrate working of
# Minimum value pairing for dictionary keys
# Using dict() + sorted() + zip() + lambda
# initializing lists
test_list1 = [4, 7, 4, 8, 7, 9]
test_list2 = [5, 7, 2, 9, 3, 4]
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# using zip() to bing key and value lists
# reverse sorting the list before assigning values
# so as minimum values get to end, and hence avoided from
# pairing
res = dict(sorted(zip(test_list1, test_list2), key = lambda ele: -ele[1]))
# printing result
print("The minimum paired dictionary : " + str(res))
OutputThe original list 1 : [4, 7, 4, 8, 7, 9]
The original list 2 : [5, 7, 2, 9, 3, 4]
The minimum paired dictionary : {8: 9, 7: 3, 4: 2, 9: 4}
Time Complexity: O(n*nlogn), where n is the elements of list
Auxiliary Space: O(n), where n is the size of list
Method #2 : Using groupby() + itemgetter() + zip()
The combination of above functions provide yet another way to solve this problem. In this, the values grouping is done using groupby() and minimum element is extracted using itemgetter().
Python3
# Python3 code to demonstrate working of
# Minimum value pairing for dictionary keys
# Using groupby() + itemgetter() + zip()
from operator import itemgetter
from itertools import groupby
# initializing lists
test_list1 = [4, 7, 4, 8, 7, 9]
test_list2 = [5, 7, 2, 9, 3, 4]
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# using zip() to bind key and value lists
# groupby() to group similar value.
# 0th, first element is extracted to be smallest
# using itemgetter()
temp = sorted(zip(test_list1, test_list2))
res = {key: min(val for _, val in group)
for key, group in groupby(sorted(temp), itemgetter(0))}
# printing result
print("The minimum paired dictionary : " + str(res))
OutputThe original list 1 : [4, 7, 4, 8, 7, 9]
The original list 2 : [5, 7, 2, 9, 3, 4]
The minimum paired dictionary : {4: 2, 7: 3, 8: 9, 9: 4}
Time Complexity: O(n*n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n) where n is the number of elements in the list “test_list”.
Method 3 : using a loop
steps for this approach:
Initialize an empty dictionary res.
Loop over the indexes i of both lists test_list1 and test_list2.
Check if the current value of test_list1[i] is already a key in res. If not, add it to res with the value of test_list2[i].
If the current value of test_list1[i] is already a key in res, compare its current value to test_list2[i] and update it with the minimum of the two.
After the loop, print the resulting dictionary res.
Python3
# initializing lists
test_list1 = [4, 7, 4, 8, 7, 9]
test_list2 = [5, 7, 2, 9, 3, 4]
# initializing result dictionary
res = {}
# iterating over both lists and updating dictionary
for i in range(len(test_list1)):
if test_list1[i] not in res:
res[test_list1[i]] = test_list2[i]
else:
res[test_list1[i]] = min(res[test_list1[i]], test_list2[i])
# printing result
print("The minimum paired dictionary : " + str(res))
OutputThe minimum paired dictionary : {4: 2, 7: 3, 8: 9, 9: 4}
The time complexity of this approach is O(n), where n is the length of the lists, since it requires only one pass over both lists.
The auxiliary space complexity is O(k), where k is the number of unique keys in the dictionary, since only one value is stored for each key.
METHOD 4:Using defaultdict() and zip()
APPROACH:
This program pairs the minimum values from two given lists and creates a dictionary where the first list's values are used as keys and the corresponding minimum value from the second list is the value.
ALGORITHM:
1.Import the defaultdict module from the collections package.
2.Create two lists named list1 and list2.
3.Create a defaultdict with a lambda function that returns the maximum possible float value as the default value for any key.
4.Use zip to iterate over the two lists and compare each corresponding value from both lists.
5.If the value from list2 is less than the value already present in the defaultdict for that key, replace the value in the defaultdict with the new value.
6.Convert the defaultdict to a dictionary and print it.
Python3
from collections import defaultdict
# Original lists
list1 = [4, 7, 4, 8, 7, 9]
list2 = [5, 7, 2, 9, 3, 4]
# Pair the minimum values using defaultdict and zip
min_dict = defaultdict(lambda: float('inf'))
for k, v in zip(list1, list2):
min_dict[k] = min(min_dict[k], v)
# Print the minimum paired dictionary
print("The minimum paired dictionary:", dict(min_dict))
OutputThe minimum paired dictionary: {4: 2, 7: 3, 8: 9, 9: 4}
Time Complexity: O(n), where n is the length of the lists since we are iterating over both lists only once.
Space Complexity: O(n), where n is the length of the lists since we are storing a dictionary that can have at most n key-value pairs.
METHOD 5:Using set function.
APPROACH:
The program takes two lists as input and creates a dictionary by pairing elements from both lists. Then, it finds the minimum value for each key in the dictionary and creates a new dictionary with these minimum values.
ALGORITHM:
1. Create a dictionary using the zip() function to pair elements from the two input lists.
2. Find the unique keys in the dictionary by creating a set of the first list.
3. Loop through each unique key and find the minimum value for that key in the dictionary.
4. Create a new dictionary with the minimum value for each key.
5. Output the new dictionary.
Python3
# Input lists
list1 = [4, 7, 4, 8, 7, 9]
list2 = [5, 7, 2, 9, 3, 4]
# Creating a dictionary using zip() function
input_dict = dict(zip(list1, list2))
# Finding unique keys in the dictionary
unique_keys = set(list1)
# Finding the minimum value for each key using loop
min_dict = {}
for key in unique_keys:
min_val = float('inf')
for k, v in input_dict.items():
if k == key and v < min_val:
min_val = v
min_dict[key] = min_val
# Outputting the minimum paired dictionary
print("The minimum paired dictionary:", min_dict)
OutputThe minimum paired dictionary: {8: 9, 9: 4, 4: 2, 7: 3}
Time complexity: O(n^2), where n is the length of the input list1. The time complexity is dominated by the nested loop used to find the minimum value for each key.
Space complexity: O(n), where n is the length of the input list1. The space complexity is due to the dictionaries created in the program.
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read