Print a list of every combination of dictionary keys with the associated sum of the key values to the right
<p>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.</p>

<p>So, if I have these dictionaries:</p>

<pre><code>dict1 = {"Main": 8, "Optional": 6, "Obscure": 4}
dict2 = {"Global": 8, "Regional": 4, "Local": 2}
...
</code></pre>

<p>The output would look like this (sorted by sum highest to lowest):</p>

<pre><code>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
</code></pre>

<p>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.</p>

<p>Any help would be appreciated.</p>

<p>Thanks</p>

<p>You've read right. Just add <code>sorted()</code>:</p>

<pre><code>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=', ')
</code></pre>

python dictionary product itertools cartesian-product