Python program to find the highest 3 values in a dictionary
Last Updated :
17 May, 2023
Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair.
Examples:
Input : my_dict = {'A': 67, 'B': 23, 'C': 45,
'D': 56, 'E': 12, 'F': 69}
Output : {'F': 69, 'A': 67, 'D': 56}
Let us see different methods we can find the highest 3 values in a dictionary.
Method #1: Using collections.Counter()
A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.
most_common([n]) returns a list of the n most common elements and their counts from the most common to the least.
Python3
# Python program to demonstrate
# finding 3 highest values in a Dictionary
from collections import Counter
# Initial Dictionary
my_dict = {'A': 67, 'B': 23, 'C': 45,
'D': 56, 'E': 12, 'F': 69}
k = Counter(my_dict)
# Finding 3 highest values
high = k.most_common(3)
print("Initial Dictionary:")
print(my_dict, "\n")
print("Dictionary with 3 highest values:")
print("Keys: Values")
for i in high:
print(i[0]," :",i[1]," ")
Output: Initial Dictionary:
{'C': 45, 'B': 23, 'D': 56, 'A': 67, 'E': 12, 'F': 69}
Dictionary with 3 highest values:
Keys: Values
F : 69
A : 67
D : 56
Method #2: Using heapq.nlargest()
Python3
# Python program to demonstrate
# finding 3 highest values in a Dictionary
from heapq import nlargest
# Initial Dictionary
my_dict = {'A': 67, 'B': 23, 'C': 45,
'D': 56, 'E': 12, 'F': 69}
print("Initial Dictionary:")
print(my_dict, "\n")
ThreeHighest = nlargest(3, my_dict, key = my_dict.get)
print("Dictionary with 3 highest values:")
print("Keys: Values")
for val in ThreeHighest:
print(val, ":", my_dict.get(val))
Output: Initial Dictionary:
{'D': 56, 'E': 12, 'F': 69, 'C': 45, 'B': 23, 'A': 67}
Dictionary with 3 highest values:
Keys: Values
F : 69
A : 67
D : 56
Method #3: Using keys(),values() and sort() methods
Python3
# Python program to demonstrate
# finding 3 highest values in a Dictionary
# Initial Dictionary
my_dict = {'A': 67, 'B': 23, 'C': 45,
'D': 56, 'E': 12, 'F': 69}
print("Initial Dictionary:")
print(my_dict, "\n")
print("Dictionary with 3 highest values:")
print("Keys: Values")
x=list(my_dict.values())
d=dict()
x.sort(reverse=True)
x=x[:3]
for i in x:
for j in my_dict.keys():
if(my_dict[j]==i):
print(str(j)+" : "+str(my_dict[j]))
OutputInitial Dictionary:
{'A': 67, 'B': 23, 'C': 45, 'D': 56, 'E': 12, 'F': 69}
Dictionary with 3 highest values:
Keys: Values
F : 69
A : 67
D : 56
Method#4: Using dictionary
Convert the dictionary into a list of tuples where each tuple contains a key-value pair from the dictionary. Sort the list in descending order based on the value of the dictionary. Create a new dictionary containing the first three elements of the sorted list. Return the new dictionary as output.
Algorithm
1. Initialize an empty dictionary result_dict.
2. Convert the input dictionary into a list of tuples using the items() method.
3. Sort the list of tuples in descending order based on the value of the dictionary using the sorted() method and lambda function.
4. Loop through the sorted list up to the first 3 elements.
5. Add each tuple to the result_dict.
6. Return result_dict as output.
Python3
def highest_3_values_1(my_dict):
result_dict = {}
sorted_dict = sorted(my_dict.items(), key=lambda x: x[1], reverse=True)
for i in range(3):
result_dict[sorted_dict[i][0]] = sorted_dict[i][1]
return result_dict
my_dict = {'A': 67, 'B': 23, 'C': 45, 'D': 56, 'E': 12, 'F': 69}
print(highest_3_values_1(my_dict))
Output{'F': 69, 'A': 67, 'D': 56}
Time complexity: O(n log n) - sorting the dictionary takes O(n log n) time, where n is the number of elements in the dictionary.
Auxiliary Space: O(n) - storing the sorted list takes O(n) space, where n is the number of elements in the dictionary.
Approach#5: Using lambda
This code uses an anonymous function to sort the dictionary items by value in descending order, takes the first three items, and creates a new dictionary from them.
Algorithm
1. Initialize a dictionary my_dict with key-value pairs.
2. Use the sorted() function with the anonymous function that sorts the dictionary items by value in descending order.
3. Use slicing to take the first three items from the sorted list of dictionary items.
4. Create a new dictionary from the three items.
5. Print the new dictionary.
Python3
my_dict = {'A': 67, 'B': 23, 'C': 45, 'D': 56, 'E': 12, 'F': 69}
result = dict(sorted(my_dict.items(), key=lambda x: x[1], reverse=True)[:3])
print(result)
Output{'F': 69, 'A': 67, 'D': 56}
Time Complexity: O(n log n), because the sorted() function has a time complexity of O(n log n), where n is the number of items in the dictionary.
Auxiliary Space: O(k), where k is the number of items in the new dictionary, because the code uses additional memory to create the new dictionary.
Similar Reads
Python program to find second maximum value in Dictionary
Dictionaries in Python is same as Associative arrays or Maps in other languages. Unlike lists, dictionaries stores data in key-value pair.Let's see how to find the second maximum value in a Python dictionary.Method #1: Naive Approach: A general approach is to find the largest value of the dictionary
3 min read
Python program to find the key of maximum value tuples in a dictionary
Given a dictionary with values as tuples, the task is to write a python program to find the key of maximum value tuples. Examples: Input : test_dict = {'gfg' : ("a", 3), 'is' : ("c", 9), 'best' : ("k", 10), 'for' : ("p", 11), 'geeks' : ('m', 2)}Output : forExplanation : 11 is maximum value of tuple
6 min read
Python Program to display keys with same values in a dictionary List
Given a list with all dictionary elements, the task is to write a Python program to extract keys having similar values across all dictionaries. Examples: Input : test_list = [{"Gfg": 5, "is" : 8, "best" : 0}, {"Gfg": 5, "is" : 1, "best" : 0}, {"Gfg": 5, "is" : 0, "best" : 0}] Output : ['Gfg', 'best'
5 min read
Python program to find Maximum value from dictionary whose key is present in the list
Given a list with dictionary keys and a dictionary, extract maximum from dictionary values, whose key is present in list. Examples: Input : test_dict = {"Gfg": 4, "is" : 5, "best" : 10, "for" : 11, "geeks" : 3}, test_list = ["Gfg", "best", "geeks"] Output : 10 Explanation : Max value is 11, but not
6 min read
Python program to group keys with similar values in a dictionary
Given a dictionary with values as a list. Group all the keys together with similar values. Input : test_dict = {"Gfg": [5, 6], "is": [8, 6, 9], "best": [10, 9], "for": [5, 2], "geeks": [19]} Output : [['Gfg', 'is', 'for'], ['is', 'Gfg', 'best'], ['best', 'is'], ['for', 'Gfg']] Explanation : Gfg has
2 min read
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 Pyt
2 min read
Python | N largest values in dictionary
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() + it
5 min read
Python | Least Value test in Dictionary
While working with dictionary, we might come to a problem in which we require to ensure that all the values are atleast K in dictionary. This kind of problem can occur while checking status of start or checking for a bug/action that could have occurred. Letâs discuss certain ways in which this task
7 min read
Python program to Sort a List of Dictionaries by the Sum of their Values
Given Dictionary List, sort by summation of their values. Input : test_list = [{1 : 3, 4 : 5, 3 : 5}, {1 : 100}, {8 : 9, 7 : 3}] Output : [{8: 9, 7: 3}, {1: 3, 4: 5, 3: 5}, {1: 100}] Explanation : 12 < 13 < 100, sorted by values sum Input : test_list = [{1 : 100}, {8 : 9, 7 : 3}] Output : [{8:
6 min read
Set from Dictionary Values - Python
The task is to extract unique values from a dictionary and convert them into a set. In Python, sets are unordered collections that automatically eliminate duplicates. The goal is to extract all the values from the dictionary and store them in a set.For example, given a dictionary like d = {'A': 4, '
3 min read