
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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.
- Related Articles
- Python – Replace value by Kth index value in Dictionary List
- Sort Dictionary key and values List in Python
- Python – Convert List to Index and Value dictionary
- Sort Python Dictionaries by Key or Value
- How to sort a Python dictionary by value?
- Python – Extract Key’s Value, if Key Present in List and Dictionary
- Accessing Key-value in a Python Dictionary
- Dictionary with index as value in Python
- Get key from value in Dictionary in Python
- Python - Clearing list as dictionary value
- Convert key-values list to flat dictionary in Python
- What is possible key/value delimiter in Python dictionary?
- Add a key value pair to dictionary in Python
- Get key with maximum value in Dictionary in Python
- How to sort a Python dictionary by datatype?

Advertisements