📜  Python|字典中的选择性键值

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

Python|字典中的选择性键值

有时在使用Python字典时,我们可能会遇到需要从字典中获取选择性键值的问题。此问题可能发生在 Web 开发领域。让我们讨论一些可以解决这个问题的方法。

方法 #1:使用列表理解 + get()
上述功能的组合可用于执行此特定任务。在此,我们使用get方法访问值并使用列表推导遍历字典。

# Python3 code to demonstrate working of
# Selective key values in dictionary
# Using list comprehension + get()
  
# Initialize dictionary
test_dict = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 4, 'CS' : 5}
  
# printing original dictionary
print("The original dictionary : " +  str(test_dict))
  
# Initialize key list 
key_list = ['gfg', 'best', 'CS']
  
# Using list comprehension + get()
# Selective key values in dictionary
res = [test_dict.get(key) for key in key_list]
      
# printing result 
print("The values of Selective keys : " + str(res))
输出 :

方法 #2:使用itemgetter()
这个单一的函数可以用来执行这个特定的任务。它内置执行此特定任务。它接受键链并将相应的值作为可以进行类型转换的元组返回。

# Python3 code to demonstrate working of
# Selective key values in dictionary
# Using itemgetter()
from operator import itemgetter
  
# Initialize dictionary
test_dict = {'gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 4, 'CS' : 5}
  
# printing original dictionary
print("The original dictionary : " +  str(test_dict))
  
# Initialize key list 
key_list = ['gfg', 'best', 'CS']
  
# Using itemgetter()
# Selective key values in dictionary
res = list(itemgetter(*key_list)(test_dict))
      
# printing result 
print("The values of Selective keys : " + str(res))
输出 :