# Python program to extract N largest dictionaries keys

A python dictionary is a data structure that can be used for numerous operations making it a prolific programming tool. It stores data in the form of key-value pairs i.e., each data can be labelled with a unique key. Keys in dictionaries are identifiers that are associated with different values, these values can be accessed, modified and deleted.

Based on the task, keys can be sorted and extracted in different orders. In this article, we will be discussing a similar concept of extracting N largest dictionaries keys. We will operate on these unique keys and extract the relevant data.

## Understanding the Problem

Consider a dictionary with random unique key values, our task is to segregate largest N keys from a dictionary. Let’s understand this with the help of an example −

### Input Output Scenarios

Let us consider a dictionary with the following values −

Input:
dict1 = {12 : 10, 22 : 12, 18 : 4, 4 : 8, 20 : 14, 9 : 13}


If the value of N is 4, then the 4 largest key values from the original dictionary should be returned.

Output: [22, 20, 18, 12]


Max N key values are returned. Now that we have understood the problem statement, let’s discuss a few solutions.

## Using Iterations and Max()

This is a basic approach of extracting N largest keys from a dictionary. We will create a dictionary and two empty lists that will store the maximum values and the reference values respectively. After this, we will pass the “N” value and extract the key values with the help of iterations and the “.items()” method.

These extracted values will be stored in a list (Maxlis). We will again iterate over the appended dictionary keys “N” times and extract all the maximum values. On each iteration, the maximum key value will be removed from the list and the list (Nlargest) with the largest N keys will be printed.

### Example

Following is an example to extract N largest dictionary keys using iterations and appending −

dict1 = {12 : 10, 22 : 12, 18 : 4, 4 : 8, 20 : 14, 9 : 13}
Maxlis = []
N = 4
Nlargest = []
print(f"The original dictionary is: {dict1}")

for keys, values in dict1.items():
Maxlis.append(keys)

for x in range(N):
maxval = max(Maxlis)
Nlargest.append(maxval)
Maxlis.remove(maxval)

print(f"The list of N largest dictionaries keys: {Nlargest}")


### Output

The original dictionary is: {12: 10, 22: 12, 18: 4, 4: 8, 20: 14, 9: 13}
The list of N largest dictionaries keys: [22, 20, 18, 12]


## Using Iteration along with Sorted() + Lambda

This is an advanced approach of extracting the N largest keys. In this approach, we will retrieve all the dictionary keys using iteration and “.items()” method. We will use the “key” parameter in the “sorted()” function to specify another function (lambda) that will handle the extraction logic. The lambda function extract the keys and the sorted() function sort them in order.

The “reverse = True” clause sorts the key values in descending order. Finally, we use the slicing technique to extract only the first N keys from the dictionary and store them in a list (Nlargest).

### Example

Following is an example −

dict1 = {12 : 10, 22 : 12, 18 : 4, 4 : 8, 20 : 14, 9 : 13}
N = 4
Nlargest = []
print(f"The original dictionary is: {dict1}")

for keys, values in sorted(dict1.items(), key = lambda item : item,
reverse = True) [:N]:
Nlargest.append(keys)
print(f"The N largest keys are: {Nlargest}")


### Output

The original dictionary is: {12: 10, 22: 12, 18: 4, 4: 8, 20: 14, 9: 13}
The N largest keys are: [22, 20, 18, 12]


## Using Sorted() + Itemgetter()

Instead of using lambda function for item extraction, we can use the “itemgetter()” function from the operator module. We will use the same concept of iterating and sorting the keys but the “key” parameter will assign the “itemgetter()” function for the extraction of keys.

### Example

Following is an example −

from operator import itemgetter
dict1 = {12 : 10, 22 : 12, 18 : 4, 4 : 8, 20 : 14, 9 : 13}
N = 4
Nlargest = []
print(f"The original dictionary is: {dict1}")

for keys, values in sorted(dict1.items(), key = itemgetter(0),
reverse = True) [:N]:
Nlargest.append(keys)
print(f"The N largest keys are: {Nlargest}")


### Output

The original dictionary is: {12: 10, 22: 12, 18: 4, 4: 8, 20: 14, 9: 13}
The N largest keys are: [22, 20, 18, 12]


## Other Solutions and Insights

There are several techniques that can be used to extract largest N keys from a dictionary including the use “nlargest()” function from “heapq” module and function based sorting. The setting up of the right value for the “lambda” and “itemgetter” functions is very crucial as it establishes the base for item sorting and extraction.

## Conclusion

During the course of this article, we discussed numerous solutions to extract N largest dictionaries value. We began with a basic and brute approach of segregating and appending the largest keys. After this, we discussed some advanced solutions to produce a meticulous and optimized program. We understood the application of sorted(), lambda, itemgetter and max() functions.

Updated on: 12-Jul-2023

50 Views 