'Subset sum problem using key value pairs - python

I have an algorithm that outputs a subset which sums up to a value as close to integer s as possible

from itertools import combinations

products = {
    "Apple": 5,
    "Pear": 4,
    "Banana": 8,
    "Strawberry": 7,
    "Watermelon": 9,
    "Lemon": 6,
}


def closest_subset(s, nums):
    return min((
        c
        for i in range(1, len(nums) + 1)
        for c in combinations(nums, i)
    ), key=lambda x: abs(s - sum(x)))


print(closest_subset(11, products.values()))

# Output: (5, 6)

Instead, I would like to output items from the dictionary, like this:

# Desired output
{
    "Apple": 5,
    "Lemon": 6,
}

How can I modify my code to achieve this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source