Extracting n Largest Dictionary Keys in Python

In this task, we are going to solve a task of extracting n number of dictionary keys in descending order in Python. Further for this, we will use the solved(), lambda, and reverse functions. First, let’s know what are Python dictionaries in short.

Dictionaries are data structures of Python and it consists of a collection of key-value pairs. In other words, keys are mapped to their respective values and these keys are used to access the values.

Now, we see that we need some functions named sorted(), lambda and reverse for our task. Let us first discuss these before proceeding deeper with the concept!!

What are Sorted(), Reverse and Lambda functions?

Sorted() is an in-built Python function that sorts any kind of sequence and always returns the sorted sequence in the form of a list. Moreover, it consists of three parameters: iterable, key, and reverse. The syntax for sorted() is as follows :

sorted (  iterable ,  key ,  reverse )

where,

  • iterable : the sequence that has to be sorted and returned as a list
  • key : this takes function as its value and serves as a basis on which the sorting of the sequence will be done.
  • reverse : the sorted() function originally returns output in ascending order. On using reverse =True, the output will become in descending order.

For example :

listed = ["bb","cccc","a","ddd"]
print(sorted(listed,key=len))
print(sorted(listed))

Output :

["a","bb","ddd","cccc"]

["a","bb","cccc","ddd"]

The Lambda function is a one-line function that has no name. Hence, it is denoted with the keyword ‘lambda‘. A lambda function can have more than one argument but has only one expression. The advantage of lambda is that it is not required to write the entire function in lambda, hence maintains the clarity of code. The syntax for lambda is :

lambda arguments : an expression

For example :

double = lambda x:x+9
print(double(5))

Output :

14

The key of sorted() function takes lambda function as its value and the expression of lambda will denote what will be the basis on which the sorting occurs.

Implementation in Given Task

In this task, we will perform extraction of num no. of keys from the Python dictionary in descending order. Here, we will take n as input but the user can take n as any default value as well. The approach is as follows :

  • First, we initialize dict_int with the dictionary(as per the wish of the user) whose keys are to be sorted.
  • Next, we take the num,that is, the number of keys to be printed, as input.
  • Initialize a new list st with [].
  • Run a for loop where k and v serve as the variables for key and value for extracting the keys. In addition to this, take the range as the sorted dictionary in the form of a list.
  • Inside the sorted() function, the iterable is considered dict_int.items(). The items() function returns a dict_int in the form of a list with the combination of keys of values intact. Take the key as lambda ele: ele[0]. The 0 represents the key portion of the list; this means that the list will now be sorted with respect to the keys in ascending order. The reverse function is taken True for reversing the list.
  • The sorted list is then considered till num before using it as range.
  • Append the k to the empty string st with the loop.
  • Print st.
# initializing dictionary 
dict_int = {1 : 20, 2: 50, 3: 90, 5: 60} 
  
# initializing the number of keys to be printed 
num = int(input("Enter the number: "))
st= [] 
# 0 to denote sort by keys
for k, v in sorted(dict_int.items(), key = lambda e: e[0], reverse = True)[:num]: 
    st.append(k)   
print( str(st))

Output :

Enter the number: 4
[5, 3, 2, 1]

Here, we took the dictionary as {1 : 20, 2 : 50, 3 : 90, 5 : 60} and the num as 4. Therefore, we got the output for it with all the keys printed as a list in their descending order.

Thank you for going through this article. You can also check the related articles below :

 

Leave a Reply

Your email address will not be published. Required fields are marked *