📜  Python|提取过滤的字典值

📅  最后修改于: 2022-05-13 01:54:34.522000             🧑  作者: Mango

Python|提取过滤的字典值

在使用Python字典时,有时我们只关心获取过滤后的值列表而不关心键。这是另一个重要的实用程序和解决方案,应该知道和讨论。让我们通过某些方法来执行此任务。

方法#1:使用循环+ keys()
实现此任务的第一个方法是使用循环访问每个过滤键的值并将其附加到列表中并返回它。这可以是执行此任务的方法之一。

# Python3 code to demonstrate working of
# Extract filtered Dictionary Values
# Using loop + keys()
  
# initializing dictionary
test_dict = {'gfg' : 1, 'is' : 2, 'best' : 3}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing K 
K = 2
  
# Extract filtered Dictionary Values
# Using loop + keys()
res = []
for key in test_dict.keys() :
    if test_dict[key] >= K:
        res.append(test_dict[key])
  
# printing result
print("The list of filtered values is : " + str(res))
输出 :
The original dictionary is : {'best': 3, 'gfg': 1, 'is': 2}
The list of filtered values is : [3, 2]

方法 #2:使用values()
也可以使用 values() 的内置函数来执行此任务。这是执行此特定任务并返回过滤后的确切期望结果的最佳和最 Pythonic 方式。

# Python3 code to demonstrate working of
# Extract filtered Dictionary Values
# Using values()
  
# initializing dictionary
test_dict = {'gfg' : 1, 'is' : 2, 'best' : 3}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing K 
K = 2
  
# Extract filtered Dictionary Values
# Using values()
temp = list(test_dict.values())
res = [ele for ele in temp if ele >= K]
  
# printing result
print("The list of filtered values is : " + str(res))
输出 :
The original dictionary is : {'best': 3, 'gfg': 1, 'is': 2}
The list of filtered values is : [3, 2]