identical123456 identical123456 - 2 months ago 15
Python Question

Unsupported operand type for - list and list

I am using an older version of python which doesnt have support to subtract dict's.

d1={'ab': ['3'], 'hij': ['1200']}
d2={'ab': ['1'], 'hij': ['600']}


Basically my code looks like this:

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


output should be like

d2={'ab': ['2'], 'hij': ['600']}


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

Answer

Get the first values from the list and cast them to ints.

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

Output:

{'hij': 600, 'ab': 2}

To support floats, you need to cast to float. If you want to have 4 digits of precision, then you can use the round function.

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

Output:

{'hij': 599.971, 'ab': 1.8995}