Python | N largest values in dictionary
Last Updated :
08 May, 2023
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
from operator import itemgetter
test_dict = { 'gfg' : 1 , 'is' : 4 , 'best' : 6 , 'for' : 7 , 'geeks' : 3 }
N = 3
print ( "The original dictionary is : " + str (test_dict))
res = dict ( sorted (test_dict.items(), key = itemgetter( 1 ), reverse = True )[:N])
print ( "The top N value pairs are " + str (res))
|
Output :
The original dictionary is : {'best': 6, 'gfg': 1, 'geeks': 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
from heapq import nlargest
test_dict = { 'gfg' : 1 , 'is' : 4 , 'best' : 6 , 'for' : 7 , 'geeks' : 3 }
N = 3
print ( "The original dictionary is : " + str (test_dict))
res = nlargest(N, test_dict, key = test_dict.get)
print ( "The top N value pairs are " + str (res))
|
Output :
The original dictionary is : {'gfg': 1, 'best': 6, 'geeks': 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
test_dict = { 'gfg' : 1 , 'is' : 4 , 'best' : 6 , 'for' : 7 , 'geeks' : 3 }
N = 3
print ( "The original dictionary is : " + str (test_dict))
res = dict ( sorted (test_dict.items(), key = lambda x: x[ 1 ], reverse = True )[:N])
print ( "The top N value pairs are " + str (res))
|
Output
The original dictionary is : {'gfg': 1, 'is': 4, 'best': 6, 'for': 7, 'geeks': 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
test_dict = { 'gfg' : 1 , 'is' : 4 , 'best' : 6 , 'for' : 7 , 'geeks' : 3 }
N = 3
print ( "The original dictionary is : " + str (test_dict))
res = dict ( sorted (test_dict.items(), key = lambda x: x[ 1 ], reverse = True )[:N])
print ( "The top N value pairs are " + str (res))
|
Output
The original dictionary is : {'gfg': 1, 'is': 4, 'best': 6, 'for': 7, 'geeks': 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 , 'geeks' : 3 , 'for' : 7 , 'is' : 4 }
n = 3
counter = Counter(dict1)
result = dict (counter.most_common(n))
print ( "The top N value pairs are " , result)
|
Output
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.
Similar Reads
Second largest value in a Python Dictionary
In this problem, we will find the second-largest value in the given dictionary. Examples: Input : {'one':5, 'two':1, 'three':6, 'four':10} Output : Second largest value of the dictionary is 6 Input : {1: 'Geeks', 'name': 'For', 3: 'Geeks'} Output : Second largest value of the dictionary is Geeks C/C
2 min read
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 - Value length dictionary
Sometimes, while working with a Python dictionary, we can have problems in which we need to map the value of the dictionary to its length. This kind of application can come in many domains including web development and day-day programming. Let us discuss certain ways in which this task can be perfor
4 min read
Python - Maximum Value in Nested Dictionary
Sometimes, while working with python dictionary, we can have problem in which each key in itself is a record with several keys and we desire to substitute the value as maximum value of keys of dictionary. This kind of problem can have application in many domains that involves data. Lets discuss cert
4 min read
Get List of Values From Dictionary - Python
We are given a dictionary and our task is to extract all the values from it and store them in a list. For example, if the dictionary is d = {'a': 1, 'b': 2, 'c': 3}, then the output would be [1, 2, 3]. Using dict.values()We can use dict.values() along with the list() function to get the list. Here,
2 min read
Python - Dictionary List Values Frequency
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform the task of computing frequency of all the values in dictionary values lists. This is quite common problem and can have use cases in many domains. Let's discuss certain ways in which this task can be
6 min read
Python - Key Value list pairings in Dictionary
Sometimes, while working with Python dictionaries, we can have problems in which we need to pair all the keys with all values to form a dictionary with all possible pairings. This can have application in many domains including day-day programming. Lets discuss certain ways in which this task can be
7 min read
Get Index of Values in Python Dictionary
Dictionary values are lists and we might need to determine the position (or index) of each element within those lists. Since dictionaries themselves are unordered (prior to Python 3.7) or ordered based on insertion order (in Python 3.7+), the concept of "index" applies to the valuesâspecifically whe
3 min read
Python - Dictionary items in value range
In this article, we will explore different methods to extract dictionary items within a specific value range. The simplest approach involves using a loop. Using LoopThe idea is to iterate through dictionary using loop (for loop) and check each value against the given range and storing matching items
2 min read
Python - Unique Values of Key in Dictionary
We are given a list of dictionaries and our task is to extract all the unique values associated with a given key. For example, consider: data = [ {"name": "Aryan", "age": 25}, {"name": "Harsh", "age": 30}, {"name": "Kunal", "age": 22}, {"name": "Aryan", "age": 27}]key = "name" Then, the unique value
4 min read