Brandon Brandon - 11 months ago 53
Python Question

Print a list of every combination of dictionary keys with the associated sum of the key values to the right

I have several dictionaries and I want to print a table where each row is a unique combination of the keys in all dictionaries. For each row, I also want to print the sum of the values for the keys in that particular combination.

So, if I have these dictionaries:

dict1 = {"Main": 8, "Optional": 6, "Obscure": 4}
dict2 = {"Global": 8, "Regional": 4, "Local": 2}

The output would look like this (sorted by sum highest to lowest):

Main, Global, 16
Optional, Global, 14
Main, Regional, 12
Obscure, Global, 12
Main, Local, 10
Optional, Regional, 10
Optional, Local, 8
Obscure, Regional, 8
Obscure, Local, 6

From what I've read, itertools.product will be what I'm looking for, but none of the existing questions are quite my use case and I'm struggling to even get started.

Any help would be appreciated.


Answer Source

You've read right. Just add sorted():

from itertools import product
from operator import itemgetter

results = [(k1, k2, dict1[k1] + dict2[k2])
           for k1, k2 in product(dict1.keys(), dict2.keys())]

for k1, k2, sum_ in sorted(results, key=itemgetter(2), reverse=True): 
    print(k1, k2, sum_, sep=', ')