📜  Python|字典中的前缀键匹配

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

Python|字典中的前缀键匹配

有时,在使用字典时,我们可能会遇到一个问题,即我们需要找到对键有一些约束的字典项。一个这样的约束可以是键的前缀匹配。让我们讨论可以执行此任务的某些方式。

方法#1:使用字典理解+ startswith()
上述两种方法的组合可用于执行此特定任务。在此,字典理解完成字典构造的基本任务, startswith()执行检查以特定前缀开头的键的实用任务。

# Python3 code to demonstrate working of
# Prefix key match in dictionary
# Using dictionary comprehension + startswith()
  
# Initialize dictionary
test_dict = {'tough' : 1, 'to' : 2, 'do' : 3, 'todays' : 4, 'work' : 5}
  
# printing original dictionary
print("The original dictionary : " +  str(test_dict))
  
# Initialize prefix 
test_pref = 'to'
  
# Using dictionary comprehension + startswith()
# Prefix key match in dictionary
res = {key:val for key, val in test_dict.items() 
                   if key.startswith(test_pref)}
  
# printing result 
print("Filtered dictionary keys are : " + str(res))
输出 :

方法 #2:使用map() + filter() + items() + startswith()
也可以使用上述功能的组合来执行此特定任务。 map函数将startswith()的过滤逻辑与items()提取的每个字典的项目联系起来

# Python3 code to demonstrate working of
# Prefix key match in dictionary
# Using map() + filter() + items() + startswith()
  
# Initialize dictionary
test_dict = {'tough' : 1, 'to' : 2, 'do' : 3, 'todays' : 4, 'work' : 5}
  
# printing original dictionary
print("The original dictionary : " +  str(test_dict))
  
# Initialize prefix 
test_pref = 'to'
  
# Using map() + filter() + items() + startswith()
# Prefix key match in dictionary
res = dict(filter(lambda item: item[0].startswith(test_pref),
                                          test_dict.items()))
  
# printing result 
print("Filtered dictionary keys are : " + str(res))
输出 :