Slicing a python dictionary to perform operations
<p>New 2.7 user. I have the following dictionary:   </p>

<pre><code> dict1 = {'A': {'val1': '5', 'val2': '1'},
          'B': {'val1': '10', 'val2': '10'},
          'C': {'val1': '15', 'val3': '100'}}
</code></pre>

<p>I have another dictionary </p>

<pre><code> dict2 = {'val1': '10', 'val2': '16'}
</code></pre>

<p>I want to subtract the values from A in dict1 from dict2 to get:</p>

<pre><code> dict3 = {'val1': '5', 'val2': '15'}
</code></pre>

<p>Just create your dict using a dict comprehension:</p>

<pre><code>d3 = {k: str(int(v) - int(dict1["A"][k])) for k, v in dict2.items()}
print(d3)
</code></pre>

<p>Which would give you:</p>

<pre><code> {'val2': '15', 'val1': '5'}
</code></pre>

<p><code>for k, v in dict2.items()</code> iterates over the key/value pairs from <em>dict2</em> then we access the corresponding value from <em>dict1's "A"</em> dict  with <code>dict1["A"][k])</code> and subtract.</p>

<p>If you plan on doing calculations like that you may be as well to store the values as actual ints, not strings.</p>

python dictionary