Open In App

Python – Minimum value pairing for dictionary keys

Last Updated : 18 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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))


Output

The 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))


Output

The 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))


Output

The 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))


Output

The 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)


Output

The 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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads