Open In App

Python program to extract N largest dictionaries keys

Improve
Improve
Like Article
Like
Save
Share
Report

Given a dictionary, extract the largest N dictionaries keys in descending order.

Input : test_dict = {6 : 2, 8: 9, 3: 9, 10: 8}, N = 3 
Output : [10, 8, 6] 
Explanation : Max. N keys extracted in descending order.
Input : test_dict = {6 : 2, 8: 9, 3: 9, 10: 8}, N = 2 
Output : [10, 8] 
Explanation : Max. N keys extracted in descending order. 

Method #1 : Using sorted() + lambda + reverse

The combination of the above functions can be used to solve this problem. In this, we perform sort by keys using sorted() + lambda, and reverse is used to perform reverse sort for getting required ordering.

Python3




# Python3 code to demonstrate working of
# Extract top N Dictionaries by Key
# Using sorted() + lambda + reverse
 
# initializing dictionary
test_dict = {6: 2, 8: 9, 3: 9, 10: 8}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing N
N = 4
 
res = []
 
# 0 in lambda used for keys, list sliced till N for top N values
for key, val in sorted(test_dict.items(), key=lambda x: x[0], reverse=True)[:N]:
    res.append(key)
 
# printing result
print("Top N keys are: " + str(res))


Output

The original dictionary is : {6: 1, 8: 9, 3: 9, 10: 8}
Top N keys are: [10, 8, 6, 3]

The time complexity of the provided code is O(n log n), where n is the size of the dictionary test_dict.

The auxiliary space complexity of the provided code is O(N), where N is the number of keys to extract from the dictionary. 

Method #2 : Using nlargest() + lambda

This is yet another way in which this task can be performed. In this, maximum values are extracted using nlargest(), and lambda function is used to drive the keys extraction and comparison logic.

Python3




# Python3 code to demonstrate working of
# Extract top N Dictionaries by Key
# Using nlargest() + lambda
from heapq import nlargest
 
# initializing dictionary
test_dict = {6: 2, 8: 9, 3: 9, 6: 1, 10: 8}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing N
N = 4
 
res = []
 
# Using nlargest() to get maximum keys
for key, val in nlargest(N, test_dict.items(), key=lambda ele: ele[0]):
    res.append(key)
 
# printing result
print("Top N keys are: " + str(res))


Output

The original dictionary is : {6: 1, 8: 9, 3: 9, 10: 8}
Top N keys are: [10, 8, 6, 3]

Method#3: Using a loop and max() 

Approach: This approach involves using a loop to repeatedly find the key with the maximum value in the dictionary, append it to a list of largest keys, and remove the key-value pair from the dictionary. This process is repeated N times to obtain the N largest keys. This approach has a time complexity of O(NK), where N is the number of keys to be extracted and K is the number of keys in the dictionary, and a space complexity of O(N) for storing the N largest keys.

Algorithm:

1. Initialize an empty list to store the N largest keys.
2. Repeat the following steps N times:
a. Find the key with the maximum value in the dictionary.
b. Append the key to the list of largest keys.
c. Remove the key-value pair from the dictionary.
3. Return the list of largest keys.

Python3




def extract_N_largest_keys(test_dict, N):
    largest_keys = []
    for i in range(N):
        # Find the key with the maximum value in the dictionary.
        max_key = max(test_dict, key=test_dict.get)
        # Append the key to the list of largest keys.
        largest_keys.append(max_key)
        # Remove the key-value pair from the dictionary.
        del test_dict[max_key]
    return largest_keys
 
 
test_dict = {6: 2, 8: 9, 3: 9, 6: 1, 10: 8}
N = 4
print(extract_N_largest_keys(test_dict, N))


Output

[8, 3, 10, 6]

Time complexity: O(NK) for N iterations and K keys in the dictionary.
Auxiliary Space: O(N) for storing the N largest keys.

Method #5: Using heapq.nlargest()

  1. Import the heapq module.
  2. Define the extract_N_largest_keys() function that takes two arguments: test_dict and N.
  3. Use the heapq.nlargest() function to find the N largest keys in the dictionary. Pass the N parameter to nlargest() to specify the number of largest keys to extract. Pass the dictionary items and a lambda function that returns the second element of each item (i.e., the value) as the sorting key. Set the key parameter to None to extract the largest keys based on their values, not their keys.
  4. Return the list of largest keys.

Python3




import heapq
 
def extract_N_largest_keys(test_dict, N):
    largest_keys = heapq.nlargest(N, test_dict, key=lambda k: test_dict[k])
    return largest_keys
 
test_dict = {6: 2, 8: 9, 3: 9, 6: 1, 10: 8}
N = 4
print(extract_N_largest_keys(test_dict, N))


Output

[8, 3, 10, 6]

Time complexity of both the sorted() and nlargest() functions is O(NlogN), where N is the number of items in the dictionary. 
Auxiliary Space of both the sorted() and nlargest() functions is O(N), where N is the number of items in the dictionary.



Last Updated : 13 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads