Q:

How to sort through keys in a dictionary, adding the values and returning a list of keys if combined values equal a certain number

I have a dictionary of keys that have different integer values, e.g. 
d = {'a':1, 'b':12, 'c':33, 'd':40, 'e':15, 'f':6, 'g':27}

I want to be able to return a list of keys whose combined values equal a certain number, e.g.
number = 55
result = ['d', 'e']

I'm not sure how to approach the problem, or whether I should be thinking about it iteratively or recursively.  I'm at a bit of a loss on this one.
At the moment I am working in Python 2.7, but wouldn't mind seeing solutions in Python 3 as well.
To be honest, even suggestions would be appreciated at this stage.

A:

As long as the number of items isn't too large, you can brute-force this:
import itertools
def matches(d, target):
    # First try single items, then couples, then triplets etc.
    for num in range(1,len(d)+1):
        # Iterate over all possible combinations of length num
        for com in itertools.combinations(d.items(), num):
            # Does the sum of all second items per key/value pair match the target?
            if sum(item[1] for item in com) == target:
                # Yield one item at a time, so the caller can decide when to stop
                yield com

You can use it to iterate over all matches:
>>> mydict = {'a':1, 'b':12, 'c':33, 'd':40, 'e':15, 'f':6, 'g':27}
>>> for match in matches(mydict,55):
...     print(match)
...
(('d', 40), ('e', 15))
(('c', 33), ('e', 15), ('f', 6), ('a', 1))
(('b', 12), ('e', 15), ('g', 27), ('a', 1))

or add a break after the print() line to make your program stop at the first match.

