BMENRohan BMENRohan - 1 year ago 72
Python Question

Is it possible to split a dictionary and group the values then return each group with respective key?

If I have a dictionary {A:12, B:3, C:14, D:15, E:21, F:9, G:16} and a function that accepts a list and groups numbers based on if they add to 30. I would like my output to be a list of the keys that correspond to the group:
[A, B, D] [C,G] [E,F] (all of the values for these keys add up to 30)

So far I've been splitting the dictionary into two lists and then zipping them back together after the function, but I lose the order and everything gets scattered.

Answer Source

StackOverflow is not, of course, a code-writing service, but I'd make an exception because of the interesting problem you've got.

I'd use itertools.combinations() multiple times for different r values, to get the combinations of all possible lengths. Then, I'd sum the values and collect the results if sum is 30:

from itertools import combinations

d = {'A':12, 'B':3, 'C':14, 'D':15, 'E':21, 'F':9, 'G':16}

result = []
for l in range(2, len(d)):
    for x in combinations(d.items(), l):
        keys = []
        sum_values = 0

        for key, value in x:
            sum_values += value

        if sum_values == 30:



[['F', 'E'], ['C', 'G'], ['A', 'B', 'D']]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download