# Python – Dictionary Keys whose Values summation equals K

• Last Updated : 18 Jan, 2023

Given a dictionary and a value K, extract keys whose summation of values equals K.

Input : {“Gfg” : 3, “is” : 5, “Best” : 9, “for” : 8, “Geeks” : 10}, K = 17 Output : [‘Best’, ‘for’] Explanation : 9 + 8 = 17, hence those keys are extracted. Input : {“Gfg” : 3, “is” : 5, “Best” : 9, “for” : 8, “Geeks” : 10}, K = 19 Output : [‘Best’, ‘Geeks’] Explanation : 9 + 10 = 19, hence those keys are extracted.

Method #1 : Using loop

This is one of the ways in which this task can be performed. In this, we iterate for all the keys, and next keys in inner list, and keep on checking values summation. If its equal to K. The keys are stored.

## 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))`

Output

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

Method #2 : Using list comprehension

This is yet another way in which this task can be performed. In this, we perform task similar to above method but in shorthand manner using list comprehension.

## 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))`

Output

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

Method #3 : Using orderedDict + two pointer approach

In this approach, we first create an ordered dictionary with keys as values and values as keys. Next we use two pointer approach, one starting from 0 and other from the last index of ordered dictionary. We keep on checking if the sum of values at these two pointers is equal to K. If yes, we store the keys corresponding to these values as the result.

## Python3

 `# Python3 code to demonstrate working of``# Dictionary Keys whose Values summation equals K``# Using ordered dict and two pointer approach` `from` `collections ``import` `OrderedDict` `# 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` `# convert to ordered dict``temp_dict ``=` `OrderedDict(``sorted``(test_dict.items(), key``=``lambda` `x: x[``1``]))` `# extract keys and values``keys ``=` `list``(temp_dict.keys())``values ``=` `list``(temp_dict.values())` `res ``=` `[]``l, r ``=` `0``, ``len``(values)``-``1` `while` `l < r:``    ``if` `values[l] ``+` `values[r] ``=``=` `K:``        ``res.append([keys[l], keys[r]])``        ``l ``+``=` `1``        ``r ``-``=` `1``    ``elif` `values[l] ``+` `values[r] < K:``        ``l ``+``=` `1``    ``else``:``        ``r ``-``=` `1` `# printing result``print``(``"Keys whose sum equals K : "` `+` `str``(res))``#This code is contributed by Edula Vinay Kumar Reddy`

Output

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

This approach uses an ordered dictionary to sort the values in increasing order and then uses a two pointer approach to check if the values at the two pointers sum up to K. The time complexity of this approach is O(nlogn) and space complexity is O(n) as we are storing the keys and values in separate lists. This approach is more efficient than the above ones as it avoids nested loops and unnecessary dictionary traversals.

My Personal Notes arrow_drop_up