Python – Filter dictionaries with ordered values


When it is required to filter dictionaries with ordered values, the ‘sorted’ method along with the list comprehension is used.

Example

Below is a demonstration of the same

my_list = [{'python': 2, 'is': 8, 'fun': 10},
   {'python': 1, 'for': 10, 'coding': 9},
   {'cool': 3, 'python': 4}]

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

my_result = [index for index in my_list if sorted(
   list(index.values())) == list(index.values())]

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

Output

The list is :
[{'python': 2, 'fun': 10, 'is': 8}, {'python': 1, 'coding': 9, 'for': 10}, {'python': 4, 'cool': 3}]
The resultant dictionary is :
[{'python': 1, 'coding': 9, 'for': 10}]

Explanation

  • A list of dictionary elements is defined and is displayed on the console.

  • The list comprehension is used to iterate through the elements of the list, and the ‘sorted’ method is used to sort the list by accessing the dictionary values and checking if it is equal to the consecutive element’s value.

  • This is assigned to a variable.

  • This variable is displayed as output on the console.

Updated on: 20-Sep-2021

134 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements