📜  Python|根据选择性列表中的值过滤字典键

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

Python|根据选择性列表中的值过滤字典键

在Python中,有时我们只需要获取一些字典键,而不是全部。这个问题在 Web 开发中很常见,我们只需要从某个给定列表中获取选择性字典键。让我们讨论一些可以解决这个问题的方法。

方法#1:使用列表推导
列表推导可用于解决此特定问题。这只是执行它而不是编写循环的简写方式。

# Python3 code to demonstrate 
# getting selective dictionary keys
# using list comprehension
  
# initializing dictionary
test_dict = {"Akash" : 1, "Akshat" : 2, "Nikhil" : 3, "Manjeet" : 4}
  
# initializing selective list keys 
select_list = ['Manjeet', 'Nikhil']
  
# printing original dictionary
print ("The original dictionary is : " + str(test_dict))
  
# printing selective list 
print ("The selective list is : " + str(select_list))
  
# using list comprehension
# getting selective dictionary keys 
res = [test_dict[i] for i in select_list if i in test_dict]
  
# printing result 
print ("The selected values from list keys is : " +  str(res))
输出:


方法#2:使用set.intersection()
这是可以执行此任务的最优雅的方法。集合的交集属性可以给出可以提取的公共键,然后可以计算值。

# Python3 code to demonstrate 
# getting selective dictionary keys
# using set.intersection()
  
# initializing dictionary
test_dict = {"Akash" : 1, "Akshat" : 2, "Nikhil" : 3, "Manjeet" : 4}
  
# initializing selective list keys 
select_list = ['Manjeet', 'Nikhil']
  
# printing original dictionary
print ("The original dictionary is : " + str(test_dict))
  
# printing selective list 
print ("The selective list is : " + str(select_list))
  
# using set.intersection()
# getting selective dictionary keys 
temp = list(set(select_list).intersection(test_dict))
res = [test_dict[i] for i in temp]
  
# printing result 
print ("The selected values from list keys is : " +  str(res))
输出: