Python – 从值子字符串中提取键
有时,在使用Python字典时,我们可能会遇到一个问题,即我们需要从给定的值中找到键,从键的值中查询子字符串。这种问题很常见,并且在包括 Web 开发在内的许多领域都有应用。让我们讨论可以执行此任务的某些方式。
Input : test_dict = {1 : ‘Gfg is best’, 2 : ‘CS is best’}
Output : [1, 2]
Input : test_dict = {1 : ‘best’}
Output : [1]
方法 #1:使用循环 + items()
以上功能的组合,可以用来解决这个问题。在此,我们使用 items() 提取字典值,并使用循环使用“in”运算符检查子字符串。
# Python3 code to demonstrate working of
# Extracting Key from Value Substring
# Using loop + items()
# initializing dictionary
test_dict = {1 : 'Gfg is good', 2 : 'Gfg is best', 3 : 'Gfg is on top'}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing search_word
srch_wrd = 'best'
# Extracting Key from Value Substring
# Using loop + items()
res = []
for key, val in test_dict.items():
if srch_wrd in val:
res.append(key)
# printing result
print("The Corresponding key : " + str(res))
输出 :
The original dictionary : {1: ‘Gfg is good’, 2: ‘Gfg is best’, 3: ‘Gfg is on top’}
The Corresponding key : [2]
方法#2:使用列表推导
这是可以执行此任务的另一种方式。在此,我们以紧凑的方式在一个班轮中执行上述方法。
# Python3 code to demonstrate working of
# Extracting Key from Value Substring
# Using list comprehension
# initializing dictionary
test_dict = {1 : 'Gfg is good', 2 : 'Gfg is best', 3 : 'Gfg is on top'}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing search_word
srch_wrd = 'best'
# Extracting Key from Value Substring
# Using list comprehension
res = [key for key, val in test_dict.items() if srch_wrd in val]
# printing result
print("The Corresponding key : " + str(res))
输出 :
The original dictionary : {1: ‘Gfg is good’, 2: ‘Gfg is best’, 3: ‘Gfg is on top’}
The Corresponding key : [2]