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


if have dictionary {a:12, b:3, c:14, d:15, e:21, f:9, g:16} , function accepts list , groups numbers based on if add 30. output list of keys correspond group: [a, b, d] [c,g] [e,f] (all of values these keys add 30)

so far i've been splitting dictionary 2 lists , zipping them after function, lose order , gets scattered.

stackoverflow not, of course, code-writing service, i'd make exception because of interesting problem you've got.

i'd use itertools.combinations() multiple times different r values, combinations of possible lengths. then, i'd sum values , collect results if sum 30:

from itertools import combinations  d = {'a':12, 'b':3, 'c':14, 'd':15, 'e':21, 'f':9, 'g':16}  result = [] l in range(2, len(d)):     x in combinations(d.items(), l):         keys = []         sum_values = 0          key, value in x:             keys.append(key)             sum_values += value          if sum_values == 30:             result.append(keys)  print(result) 

prints:

[['f', 'e'], ['c', 'g'], ['a', 'b', 'd']]