📜  Python|字典中的子字符串键匹配

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

Python|字典中的子字符串键匹配

有时,在使用字典时,我们可能有一个用例,其中我们不知道我们需要的确切键,而只是我们需要获取的键的特定部分。此类问题可能出现在许多应用程序中。让我们讨论一些可以解决这个问题的方法。

方法 #1:使用items() + 列表理解
上述方法的组合可用于执行此特定任务,其中我们只需使用 items函数访问键值对,列表理解有助于迭代和访问逻辑。

# Python3 code to demonstrate working of
# Substring Key match in dictionary
# Using items() + list comprehension
  
# initializing dictionary
test_dict = {'All' : 1, 'have' : 2, 'good' : 3, 'food' : 4}
  
# initializing search key string
search_key = 'ood'
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# Using items() + list comprehension
# Substring Key match in dictionary
res = [val for key, val in test_dict.items() if search_key in key]
  
# printing result 
print("Values for substring keys : " + str(res))
输出 :
The original dictionary is : {'All': 1, 'food': 4, 'have': 2, 'good': 3}
Values for substring keys : [4, 3]

方法 #2:使用dict() + filter() + lambda
上述功能的组合可用于执行此特定任务。其中, dictfilter函数分别用于将结果转换为字典和查询列表中的子字符串。 lambda 执行访问所有键值对的任务。

# Python3 code to demonstrate working of
# Substring Key match in dictionary
# Using dict() + filter() + lambda
  
# initializing dictionary
test_dict = {'All' : 1, 'have' : 2, 'good' : 3, 'food' : 4}
  
# initializing search key string
search_key = 'ood'
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# Using dict() + filter() + lambda
# Substring Key match in dictionary
res = dict(filter(lambda item: search_key in item[0], test_dict.items()))
  
# printing result 
print("Key-Value pair for substring keys : " + str(res))
输出 :
The original dictionary is : {'have': 2, 'good': 3, 'food': 4, 'All': 1}
Key-Value pair for substring keys : {'good': 3, 'food': 4}