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>Have you tried looking at d1[key] and d2[key] to get an idea of what the error is about ? Well if not you should have, that's the first step of debugging code: looking where it failed and what was involved in the failure.</p>

<p>So the explaination of your problem is the following d1['ab'] is not a number, it is a list , that list  is <code>['3']</code> to be more precise.  So writing <code>d1['ab'] - d2['ab']</code>  translates to <code>['3'] - ['1']</code> and that would be equivalent to doing <code>list() - list()</code> and as the error states there is no way to substract two list, the operation is simply not defined. So what  you want is to take what is <strong>inside</strong> the list and not the list itself but be carefull inside those lists you only have <strong>strings</strong> not actual numbers so you have to convert the string to a number and only then you will be able to do the expected substaction.</p>

<p>But all that is fairly tedious and I assume the mistake is that you didn't totaly undersand the syntax of dictionnaries when you wrote the code. You don't have to put the numbers as strings and inside a list to put them in the dict, you could directly put the number as is : <code>d1={'ab': 3, 'hij': 1200}</code>  is perfectly valid python code. Then when you call <code>d1['ab']</code> you directly get the number you expect.</p>

python python-2.7