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>Use <code>product</code> from <code>itertools</code> on the dictionary items() where you can get the both key and value at the same time, and with the combination of key-value pairs you can construct the final result pretty straightforwardly:</p>

<pre><code>from itertools import product
sorted([(k1, k2, v1+v2) for (k1, v1), (k2, v2) in product(dict1.items(), dict2.items())], \
       key = lambda x: x[2], reverse=True)

# [('Main', 'Global', 16),
#  ('Optional', 'Global', 14),
#  ('Obscure', 'Global', 12),
#  ('Main', 'Regional', 12),
#  ('Main', 'Local', 10),
#  ('Optional', 'Regional', 10),
#  ('Obscure', 'Regional', 8),
#  ('Optional', 'Local', 8),
#  ('Obscure', 'Local', 6)]
</code></pre>

python dictionary product itertools cartesian-product