EthanT
EthanT

Reputation: 121

How to find all possible combinations of dictionary values that add up to a certain number in Python while still retaining the key names

I have a dictionary with fields having pre-assigned scores. For example, FirstNM has a score of 300. Here is a sample dictionary:

my_dictionary = dict()
my_dictionary['FirstNM'] = 300
my_dictionary['LastNM'] = 500
my_dictionary['MiddlNM'] = 700

print(my_dictionary)

{'FirstNM': 300, 'LastNM': 500, 'MiddleNM': 700}

I need to find all possible combinations of dictionary values that sum up to more than 900.

I used this code to find all the possible combinations:

values = my_dictionary.values()
keys = my_dictionary.keys()

result = [seq for i in range(len(values), 0, -1) for seq in itertools.combinations(values, i) if sum(seq) >= 900]

print(result)

[(300, 500, 700), (300, 700), (500, 700)]

How do I then re-assign the keys to the values? I've looked all over and can't make heads or tails of how to do this...Ultimately, I'd like the keys that are in the groups and not the values. Any help is much appreciated.

Desired Result:

[('FirstNM', 'LastNM', 'MiddlNM'), ('FirstNM', 'LastNM'), ('LastNM', 'MiddlNM')]

Upvotes: -1

Views: 420

Answers (1)

Alain T.
Alain T.

Reputation: 42133

Combine the keys instead of the values and map them to their values for the sum test:

result = [seq for i in range(len(values), 0, -1)
              for seq in itertools.combinations(keys, i)
              if sum(map(my_dictionary.get,seq)) >= 900]

print(result)
[('FirstNM', 'LastNM', 'MiddlNM'), ('FirstNM', 'MiddlNM'), ('LastNM', 'MiddlNM')]

Upvotes: 2

Related Questions