GeeksforGeeks App
Open App
Browser
Continue

# Python program to find the highest 3 values in a dictionary

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

Output

```Initial 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.

My Personal Notes arrow_drop_up