Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python – Filter dictionaries with ordered values
When filtering dictionaries to find those with values in ascending order, we can use the sorted() method along with list comprehension to compare the original values with their sorted version.
Syntax
[dict for dict in list_of_dicts if sorted(dict.values()) == list(dict.values())]
Example
Below is a demonstration of filtering dictionaries with ordered values ?
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)
The output of the above code is ?
The list is:
[{'python': 2, 'is': 8, 'fun': 10}, {'python': 1, 'for': 10, 'coding': 9}, {'cool': 3, 'python': 4}]
The resultant dictionary is:
[{'python': 1, 'for': 10, 'coding': 9}]
How It Works
The solution works by extracting values from each dictionary and comparing them with their sorted version:
Extract dictionary values using
dict.values()Sort the values using
sorted()Compare sorted values with original values
Keep only dictionaries where values are already in ascending order
Alternative Approach Using Lambda
You can also use the filter() function with a lambda expression ?
my_list = [{'python': 2, 'is': 8, 'fun': 10},
{'python': 1, 'for': 10, 'coding': 9},
{'cool': 3, 'python': 4}]
my_result = list(filter(lambda d: sorted(d.values()) == list(d.values()), my_list))
print("Filtered dictionaries:")
print(my_result)
Filtered dictionaries:
[{'python': 1, 'for': 10, 'coding': 9}]
Conclusion
Use list comprehension with sorted() to filter dictionaries based on ascending value order. This approach efficiently compares original values with their sorted counterparts to identify properly ordered dictionaries.
