📜  Python – 值总和等于 K 的字典键

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

Python – 值总和等于 K 的字典键

给定一个字典和一个值 K,提取值总和等于 K 的键。

方法#1:使用循环

这是可以执行此任务的方式之一。在此,我们迭代内部列表中的所有键和下一个键,并继续检查值总和。如果它等于 K。存储密钥。

Python3
# Python3 code to demonstrate working of 
# Dictionary Keys whose Values summation equals K 
# Using loop
  
# initializing dictionary
test_dict = {"Gfg" : 3, "is" : 5, "Best" : 9, "for" : 8, "Geeks" : 10}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing K 
K = 14
  
# extracting keys and values
keys = list(test_dict.keys())
values = list(test_dict.values())
  
res = None
for i in range(len(keys)):
    for j in range(i + 1, len(keys)):
  
        # checking if values equals K
        if values[i] + values[j] == K:
            res = [keys[i], keys[j]]
  
# printing result 
print("Keys whose sum equals K : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Dictionary Keys whose Values summation equals K 
# Using list comprehension 
  
# initializing dictionary
test_dict = {"Gfg" : 3, "is" : 5, "Best" : 9, "for" : 8, "Geeks" : 10}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing K 
K = 14
  
# extracting keys and values
keys = list(test_dict.keys())
values = list(test_dict.values())
  
# checking for keys in one liner
res = [[keys[i], keys[j]]  for i in range(len(keys)) for j in range(i + 1, len(keys)) if values[i] + values[j] == K]
  
# printing result 
print("Keys whose sum equals K : " + str(res))


输出
The original dictionary is : {'Gfg': 3, 'is': 5, 'Best': 9, 'for': 8, 'Geeks': 10}
Keys whose sum equals K : ['is', 'Best']

方法#2:使用列表推导

这是可以执行此任务的另一种方式。在此,我们执行与上述方法类似的任务,但使用列表理解以简写方式。

Python3

# Python3 code to demonstrate working of 
# Dictionary Keys whose Values summation equals K 
# Using list comprehension 
  
# initializing dictionary
test_dict = {"Gfg" : 3, "is" : 5, "Best" : 9, "for" : 8, "Geeks" : 10}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing K 
K = 14
  
# extracting keys and values
keys = list(test_dict.keys())
values = list(test_dict.values())
  
# checking for keys in one liner
res = [[keys[i], keys[j]]  for i in range(len(keys)) for j in range(i + 1, len(keys)) if values[i] + values[j] == K]
  
# printing result 
print("Keys whose sum equals K : " + str(res)) 
输出
The original dictionary is : {'Gfg': 3, 'is': 5, 'Best': 9, 'for': 8, 'Geeks': 10}
Keys whose sum equals K : [['is', 'Best']]