Python - 用有序值过滤字典
给定字典列表,任务是编写一个Python程序来过滤字典,其中的值按升序排列,即排序。
例子:
Input : test_list = [{‘gfg’ : 2, ‘is’ : 8, ‘good’ : 10}, {‘gfg’ : 1, ‘for’ : 10, ‘geeks’ : 9}, {‘love’ : 3, ‘gfg’ : 4}]
Output : [{‘gfg’: 2, ‘is’: 8, ‘good’: 10}, {‘love’: 3, ‘gfg’: 4}]
Explanation : 2, 8, 10 are in increasing order.
Input : test_list = [{‘gfg’ : 2, ‘is’ : 8, ‘good’ : 10}, {‘gfg’ : 1, ‘for’ : 10, ‘geeks’ : 9}, {‘love’ : 4, ‘gfg’ : 3}]
Output : [{‘gfg’: 2, ‘is’: 8, ‘good’: 10}]
Explanation : 2, 8, 10 are in increasing order.
方法 #1:使用sorted() + values() +列表理解
在这里,我们使用 sorted() 执行排序任务并使用 values() 提取值,列表理解用于执行所有字典的迭代。
Python3
# Python3 code to demonstrate working of
# Filter dictionaries with ordered values
# Using sorted() + values() + list comprehension
# initializing list
test_list = [{'gfg': 2, 'is': 8, 'good': 10},
{'gfg': 1, 'for': 10, 'geeks': 9},
{'love': 3, 'gfg': 4}]
# printing original list
print("The original list is : " + str(test_list))
# sorted to check with ordered values
# values() extracting dictionary values
res = [sub for sub in test_list if sorted(
list(sub.values())) == list(sub.values())]
# printing result
print("The filtered Dictionaries : " + str(res))
Python3
# Python3 code to demonstrate working of
# Filter dictionaries with ordered values
# Using filter() + lambda + sorted()
# initializing list
test_list = [{'gfg': 2, 'is': 8, 'good': 10},
{'gfg': 1, 'for': 10, 'geeks': 9},
{'love': 3, 'gfg': 4}]
# printing original list
print("The original list is : " + str(test_list))
# sorted to check with ordered values
# values() extracting dictionary values
# filter() and lambda function used to filter
res = list(filter(lambda sub: sorted(list(sub.values()))
== list(sub.values()), test_list))
# printing result
print("The filtered Dictionaries : " + str(res))
输出:
The original list is : [{‘gfg’: 2, ‘is’: 8, ‘good’: 10}, {‘gfg’: 1, ‘for’: 10, ‘geeks’: 9}, {‘love’: 3, ‘gfg’: 4}]
The filtered Dictionaries : [{‘gfg’: 2, ‘is’: 8, ‘good’: 10}, {‘love’: 3, ‘gfg’: 4}]
方法 #2:使用filter() + lambda + sorted()
在这里,我们使用 filter() 执行过滤任务,并且 lambda函数用于执行注入检查增加值所需的功能的任务。
蟒蛇3
# Python3 code to demonstrate working of
# Filter dictionaries with ordered values
# Using filter() + lambda + sorted()
# initializing list
test_list = [{'gfg': 2, 'is': 8, 'good': 10},
{'gfg': 1, 'for': 10, 'geeks': 9},
{'love': 3, 'gfg': 4}]
# printing original list
print("The original list is : " + str(test_list))
# sorted to check with ordered values
# values() extracting dictionary values
# filter() and lambda function used to filter
res = list(filter(lambda sub: sorted(list(sub.values()))
== list(sub.values()), test_list))
# printing result
print("The filtered Dictionaries : " + str(res))
输出:
The original list is : [{‘gfg’: 2, ‘is’: 8, ‘good’: 10}, {‘gfg’: 1, ‘for’: 10, ‘geeks’: 9}, {‘love’: 3, ‘gfg’: 4}]
The filtered Dictionaries : [{‘gfg’: 2, ‘is’: 8, ‘good’: 10}, {‘love’: 3, ‘gfg’: 4}]