Python – Sort Dictionary List by Key’s ith Index value


When it is required to sort the list of dictionary based on the key’s ‘i’th index value, the ‘sorted’ method and the lambda methods are used.

Example

Below is a demonstration of the same −

my_list = [{"Python" : "Best", "to" : "Code"},
   {"Python" : "Good", "to" : "Learn"},
   {"Python" : "object", "to" : "cool"},
   {"Python" : "oriented", "to" : "language"}]

print("The list is : " )
print(my_list)

K = "Python"
print("The value of K is ")
print(K)

i = 2
print("The value of i is :")
print(i)

my_result = sorted(my_list, key = lambda sub: sub[K][i])

print("The resultant list is : ")
print(my_result)

Output

The list is :
[{'Python': 'Best', 'to': 'Code'}, {'Python': 'Good', 'to': 'Learn'}, {'Python': 'object', 'to': 'cool'},
{'Python': 'oriented', 'to': 'language'}]
The value of K is
Python
The value of i is :
2
The resultant list is :
[{'Python': 'oriented', 'to': 'language'}, {'Python': 'object', 'to': 'cool'}, {'Python': 'Good', 'to':
'Learn'}, {'Python': 'Best', 'to': 'Code'}]

Explanation

  • A list of dictionaries is created and displayed on the console.

  • The value of 'K' is defined and is displayed on the console.

  • The value of 'i' is defined and is displayed on the console.

  • The 'sorted' method is used to sort the list using the lambda function as the key.

  • This is assigned to a variable.

  • This variable is displayed as the output on the console.

Updated on: 13-Sep-2021

309 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements