Many times while working with a Python dictionary, we can have a particular problem finding the N maxima of values in numerous keys. This problem is quite common while working in the web development domain. Let’s discuss several ways in which this task can be performed.
Method #1 : itemgetter() + items() + sorted()
The combination of the above method is used to perform this particular task. In this, we just reverse sort the dictionary values expressed using itemgetter() and accessed using items()
Python3
# Python3 code to demonstrate working of # N largest 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 N N = 3 # printing original dictionary print ( "The original dictionary is : " + str (test_dict)) # N largest values in dictionary # Using sorted() + itemgetter() + items() res = dict ( sorted (test_dict.items(), key = itemgetter( 1 ), reverse = True )[:N]) # printing result print ( "The top N value pairs are " + str (res)) |
The original dictionary is : {'best': 6, 'gfg': 1, 'Lazyroar': 3, 'for': 7, 'is': 4} The top N value pairs are {'for': 7, 'is': 4, 'best': 6}
Time complexity: O(n logn)
Auxiliary space: O(n)
Method #2: Using nlargest()
This task can be performed using the nlargest function. This is an 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 # N largest values in dictionary # Using nlargest from heapq import nlargest # Initialize dictionary test_dict = { 'gfg' : 1 , 'is' : 4 , 'best' : 6 , 'for' : 7 , 'Lazyroar' : 3 } # Initialize N N = 3 # Printing original dictionary print ( "The original dictionary is : " + str (test_dict)) # N largest values in dictionary # Using nlargest res = nlargest(N, test_dict, key = test_dict.get) # Printing result print ( "The top N value pairs are " + str (res)) |
The original dictionary is : {'gfg': 1, 'best': 6, 'Lazyroar': 3, 'for': 7, 'is': 4} The top N value pairs are ['for', 'best', 'is']
Method 3: Using lambda function with sorted() function
This approach uses a lambda function as the key argument in the sorted() function to extract the values from the dictionary and sort them in descending order.
Example:
Python3
# Initialize dictionary test_dict = { 'gfg' : 1 , 'is' : 4 , 'best' : 6 , 'for' : 7 , 'Lazyroar' : 3 } # Initialize N N = 3 # printing original dictionary print ( "The original dictionary is : " + str (test_dict)) # Sorting the dictionary by value using # lambda function to extract the values # and then reverse the sort to get the largest values first res = dict ( sorted (test_dict.items(), key = lambda x: x[ 1 ], reverse = True )[:N]) # printing result print ( "The top N value pairs are " + str (res)) #This code is contributed by Edula Vinay Kumar Reddy |
The original dictionary is : {'gfg': 1, 'is': 4, 'best': 6, 'for': 7, 'Lazyroar': 3} The top N value pairs are {'for': 7, 'best': 6, 'is': 4}
This approach’s time complexity is O(n log n) and space complexity is O(n) as it stores all the key-value pairs in a list before slicing the first N key-value pairs.
Method 4: using the heapq module
Approach:
- Import the heapq module in Python.
- Initialize the dictionary and N (same as in the given program).
- Use the nlargest() function of heapq module to get the top N items from the dictionary based on their values.
- Create a new dictionary using these top N items.
- Print the original dictionary and the new dictionary containing the top N items.
Python3
# Initialize dictionary test_dict = { 'gfg' : 1 , 'is' : 4 , 'best' : 6 , 'for' : 7 , 'Lazyroar' : 3 } # Initialize N N = 3 # printing original dictionary print ( "The original dictionary is : " + str (test_dict)) # Sort the dictionary by value using a lambda function to extract the values # and then reverse the sort to get the largest values first res = dict ( sorted (test_dict.items(), key = lambda x: x[ 1 ], reverse = True )[:N]) # printing result print ( "The top N value pairs are " + str (res)) #This code is contributed by Edula Vinay Kumar Reddy |
The original dictionary is : {'gfg': 1, 'is': 4, 'best': 6, 'for': 7, 'Lazyroar': 3} The top N value pairs are {'for': 7, 'best': 6, 'is': 4}
Time complexity: O(n log k), where n is the size of the dictionary and k is the value of N.
Auxiliary space: O(k), where k is the value of N as we are only storing the top N items in the new dictionary.
METHOD 5:Using counter method
APPROACH:
This program finds the top N value pairs in a given dictionary.
ALGORITHM:
1. Import the Counter module from collections package.
2. Define the dictionary dict1 and set the value of n to 3 (the number of top values required).
3. Create a Counter object of the dict1.
4. Using the most_common() method of the Counter object, get the N most common elements of the dictionary.
5. Convert the resulting list of tuples to a dictionary using the dict() constructor.
6. Print the resulting dictionary.
Python3
from collections import Counter dict1 = { 'best' : 6 , 'gfg' : 1 , 'Lazyroar' : 3 , 'for' : 7 , 'is' : 4 } n = 3 # number of top values counter = Counter(dict1) result = dict (counter.most_common(n)) print ( "The top N value pairs are " , result) |
The top N value pairs are {'for': 7, 'best': 6, 'is': 4}
Time Complexity: The time complexity of this program is O(n log n) due to the use of most_common() method of the Counter object.
Space Complexity: The space complexity of this program is O(n) due to the use of the result dictionary.