Python - 提取相似的键值
给定一个字典,从相似的键中提取所有值,即包含所有相似的字符,只是混在一起形成彼此。
Input : test_dict = {‘gfg’ : 5, ‘ggf’ : 19, ‘gffg’ : 9, ‘gff’ : 3, ‘fgg’ : 3}, tst_wrd = ‘fgg’
Output : [5, 19, 3]
Explanation : gfg, ggf and fgg have values, 5, 19 and 3.
Input : test_dict = {‘gfg’ : 5, ‘gffg’ : 9, ‘gff’ : 3, ‘fgg’ : 3}, tst_wrd = ‘fgg’
Output : [5, 3]
Explanation : gfg and fgg have values, 5 and 3.
方法 #1:使用 sorted() + 循环
在此,我们将排序后的键与目标键进行比较,将具有正确顺序的相似元素,并且可以检查是否相等。一旦匹配,它们的值就会被提取出来。
Python3
# Python3 code to demonstrate working of
# Extract Similar Key Values
# Using loop + sorted()
# initializing dictionary
test_dict = {'gfg': 5, 'ggf': 19, 'gffg': 9, 'gff': 3, 'fgg': 3}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing word
tst_wrd = 'fgg'
res = []
for key, val in test_dict.items():
# sorted to get similar key order
if ''.join(list(sorted(key))) == tst_wrd:
res.append(val)
# printing result
print("The extracted keys : " + str(res))
Python3
# Python3 code to demonstrate working of
# Extract Similar Key Values
# Using list comprehension + sorted()
# initializing dictionary
test_dict = {'gfg': 5, 'ggf': 19, 'gffg': 9, 'gff': 3, 'fgg': 3}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing word
tst_wrd = 'fgg'
# one-liner to solve this
res = [val for key, val in test_dict.items(
) if ''.join(list(sorted(key))) == tst_wrd]
# printing result
print("The extracted keys : " + str(res))
输出:
The original dictionary is : {‘gfg’: 5, ‘ggf’: 19, ‘gffg’: 9, ‘gff’: 3, ‘fgg’: 3}
The extracted keys : [5, 19, 3]
方法 #2:使用列表理解 + sorted()
在这里,我们执行与上面类似的任务,只需使用sorted()和列表推导使用速记来执行。
蟒蛇3
# Python3 code to demonstrate working of
# Extract Similar Key Values
# Using list comprehension + sorted()
# initializing dictionary
test_dict = {'gfg': 5, 'ggf': 19, 'gffg': 9, 'gff': 3, 'fgg': 3}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# initializing word
tst_wrd = 'fgg'
# one-liner to solve this
res = [val for key, val in test_dict.items(
) if ''.join(list(sorted(key))) == tst_wrd]
# printing result
print("The extracted keys : " + str(res))
输出:
The original dictionary is : {‘gfg’: 5, ‘ggf’: 19, ‘gffg’: 9, ‘gff’: 3, ‘fgg’: 3}
The extracted keys : [5, 19, 3]