Python – 根據順序值篩選字典
當需要使用順序值來篩選時,使用“sorted”方法和列表解析。
示例
以下對其進行演示例子
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 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}]
說明
定義了字典元素的列表,並將其顯示在控制檯中。
使用列表解析來迭代列表元素,並使用“sorted”方法透過訪問字典值並檢查它是否等於下一個元素的值來對列表進行排序。
將其分配給一個變數。
該變數在控制檯中顯示為輸出。
廣告