Saturday, November 16, 2024
Google search engine
HomeLanguagesPython – Smallest K values in Dictionary

Python – Smallest K values in Dictionary

Many times while working with Python dictionary, we can have a particular problem to find the K minima of values in numerous keys. This problem is quite common while working with web development domain. Let’s discuss several ways in which this task can be performed. 

Smallest K values in Dictionary using itemgetter() + items() + sorted()

The combination of above method is used to perform this particular task. In this, we just sort the dictionary values expressed using itemgetter() and accessed using items(). 

Python3




# Python3 code to demonstrate working of
# Smallest K values in Dictionary
# Using sorted() + itemgetter() + items()
from operator import itemgetter
 
# Initialize dictionary
test_dict = {'gfg' : 1, 'is' : 4, 'best' : 6, 'for' : 7, 'Lazyroar' : 3 }
 
# Initialize K
K = 2
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Smallest K values in Dictionary
# Using sorted() + itemgetter() + items()
res = dict(sorted(test_dict.items(), key = itemgetter(1))[:K])
 
# printing result
print("The minimum K value pairs are " + str(res))


Output

The original dictionary is : {'gfg': 1, 'is': 4, 'best': 6, 'for': 7, 'Lazyroar': 3}
The minimum K value pairs are {'gfg': 1, 'Lazyroar': 3}

Smallest K values in Dictionary Using nsmallest()

This task can be performed using the nsmallest function. This is inbuilt function in heapq library which internally performs this task and can be used to do it externally. Has the drawback of printing just keys not values. 

Python3




# Python3 code to demonstrate working of
# Smallest K values in Dictionary
# Using nsmallest
from heapq import nsmallest
 
# Initialize dictionary
test_dict = {'gfg' : 1, 'is' : 4, 'best' : 6, 'for' : 7, 'Lazyroar' : 3 }
 
# Initialize K
K = 2
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Smallest K values in Dictionary
# Using nsmallest
res = nsmallest(K, test_dict, key = test_dict.get)
 
# printing result
print("The minimum K value pairs are " + str(res))


Output

The original dictionary is : {'gfg': 1, 'is': 4, 'best': 6, 'for': 7, 'Lazyroar': 3}
The minimum K value pairs are ['gfg', 'Lazyroar']

Smallest K values in Dictionary Using sorted() + items() + lambda function

In this method, we can use the sorted() function along with the items() function and a lambda function to sort the key-value pairs based on the values and return the smallest K pairs.

Python3




# Python3 code to demonstrate working of
# Smallest K values in Dictionary
# Using sorted() + items() + lambda function
 
# Initialize dictionary
test_dict = {'gfg' : 1, 'is' : 4, 'best' : 6, 'for' : 7, 'Lazyroar' : 3 }
 
# Initialize K
K = 2
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Smallest K values in Dictionary
# Using sorted() + items() + lambda function
res = dict(sorted(test_dict.items(), key = lambda x: x[1])[:K])
 
# printing result
print("The minimum K value pairs are " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original dictionary is : {'gfg': 1, 'is': 4, 'best': 6, 'for': 7, 'Lazyroar': 3}
The minimum K value pairs are {'gfg': 1, 'Lazyroar': 3}

The time complexity of this method is O(nlogn) and Auxiliary space is O(n)
This method is similar to Method #1, but it uses a lambda function to sort the dictionary instead of the itemgetter function. The lambda function takes a tuple (key, value) and returns the value, which is used to sort the dictionary. The rest of the logic is the same as Method #1. The resulting output is the same as Method #1.

Smallest K values in Dictionary Using a custom function

Python3




# Define custom function
def get_k_smallest_values(test_dict, K):
    sorted_items = sorted(test_dict.items(), key=lambda x: x[1])
    k_smallest = {}
    for i in range(K):
        k_smallest[sorted_items[i][0]] = sorted_items[i][1]
    return k_smallest
 
# Initialize dictionary
test_dict = {'gfg' : 1, 'is' : 4, 'best' : 6, 'for' : 7, 'Lazyroar' : 3 }
 
# Initialize K
K = 2
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Get K smallest values using custom function
res = get_k_smallest_values(test_dict, K)
 
# printing result
print("The minimum K value pairs are " + str(res))


Output

The original dictionary is : {'gfg': 1, 'is': 4, 'best': 6, 'for': 7, 'Lazyroar': 3}
The minimum K value pairs are {'gfg': 1, 'Lazyroar': 3}

Time complexity: O(nlogn) for sorting the dictionary items + O(K) for iterating over the K smallest value pairs. Overall time complexity is O(nlogn).
Auxiliary space: O(K) for storing the K smallest value pairs in a dictionary.

RELATED ARTICLES

Most Popular

Recent Comments