Unsupported operand type for - list and list
<p>I am using an older version of python which doesnt have support to subtract dict's.</p>

<pre><code>d1={'ab': ['3'], 'hij': ['1200']}
d2={'ab': ['1'], 'hij': ['600']}
</code></pre>

<p>Basically my code looks like this:</p>

<pre><code>  for key in d1.keys():
        if key in d2:
            d3[key]=d1[key]-d2[key]
</code></pre>

<p>output should be like</p>

<pre><code>d2={'ab': ['2'], 'hij': ['600']}
</code></pre>

<p>It returns unsupported operand type for - : list and list.
Any ideas on how to get around this</p>

<p>Get the first values from the list and cast them to <code>int</code>s.</p>

<pre><code>d1 = {'ab': ['3'], 'hij': ['1200']}
d2 = {'ab': ['1'], 'hij': ['600']}
d3 = {}

for key in d1.keys():
    if key in d2:
        d3[key] = int(d1[key][0]) - int(d2[key][0])

print d3
</code></pre>

<p>Output:</p>

<pre><code>{'hij': 600, 'ab': 2}
</code></pre>

<hr>

<p>To support floats, you need to cast to <code>float</code>. If you want to have 4 digits of precision, then you can use the <a href="https://docs.python.org/2/library/functions.html#round" rel="nofollow"><code>round</code></a> function.</p>

<pre><code>d1 = {'ab': ['3.2462353'], 'hij': ['1200.223353']}
d2 = {'ab': ['1.346733'], 'hij': ['600.252341']}
d3 = {}

for key in d1.keys():
    if key in d2:
        num1 = float(d1[key][0])
        d3[key] = round(float(d1[key][0]) - float(d2[key][0]), 4)

print d3
</code></pre>

<p>Output:</p>

<pre><code>{'hij': 599.971, 'ab': 1.8995}
</code></pre>

python python-2.7