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>This method is built to support a variable amount of dictionaries. You pass your dictionaries to the <code>get_product_sums()</code> method, which then creates a cartesian product from the tuple of dictionaries. </p>

<p>We then iterate through our new <code>subitem</code> to calculate sums by doing a look up in our <code>flattened</code> which is just a 1D dictionary now. We then sort by the sum, and return a sorted list of tuples for our final <code>result</code>.</p>

<pre><code>from itertools import product

def get_product_sums(* args):
    result = []
    flattened = {k:v for d in args for k, v in d.items()}
    for subitem in product(* args, repeat=1):
        data = subitem + (sum(flattened[key] for key in subitem),)  
        result.append(data)
    return sorted(result, key=lambda x: x[-1], reverse=True)
</code></pre>

<p><strong>Sample Output:</strong>    </p>

<pre><code>&gt;&gt;&gt; dict1 = {"Global": 8, "Regional": 4, "Local": 2} 
&gt;&gt;&gt; dict2 = {"Main": 8, "Optional": 6, "Obscure": 4}
&gt;&gt;&gt; for item in get_product_sums(dict1, dict2):
...     print ', '.join(str(element) for element in item)
Global, Main, 16
Global, Optional, 14
Global, Obscure, 12
Regional, Main, 12
Local, Main, 10
Regional, Optional, 10
Local, Optional, 8
Regional, Obscure, 8
Local, Obscure, 6
</code></pre>

python dictionary product itertools cartesian-product