How to do Arithmetic operations between two Ordered Dictionaries in Python?

60 views Asked by At

I am trying to do arithmetic operations between two Ordered dictionaries in Python. However I am facing the error:

TypeError: unsupported operand type(s) for -: 'collections.OrderedDict' and 'int'

Below is the Python code:

from collections import OrderedDict

a = {'a_key':OrderedDict([('Max_Value', [2000]), ('Min_Value', [1000])])}
b = {'b_key':OrderedDict([('Max_Value', [1000]), ('Min_Value', [50])])}
test_dict = {key: str(round(((a[key] - b.get(key, 0))/b.get(key, 0))*100,2))+'%'
              for key in a.keys()}
print(test_dict)

Expected result: The final outcome should be assigned to test_dict. Here we want to find the percentage difference between 'Max_Value' of each provided above dictionaries (a, b). Similarly for 'Min_Value'. Both 'Max_Value' and 'Min_Value' are inside OrderedDict of the dictionaries a, b.

Expected test_dict = {'c_key': OrderedDict([('Max_Value', ['100.0%']), ('Min_Value', ['1900.0%'])])}

1

There are 1 answers

0
KrishnaSaran draksharapu On

After long struggle, I have found the desired solution by myself, on exploring a bit more. Below is the code :

from collections import OrderedDict
currentDict = {'a_key':OrderedDict([('Read_PMax', [21477]), ('Max_Read_P50', [92]), ('Avg_Read_P50', [92]), ('Max_Read_P90', [197]), ('Avg_Read_P90', [197])])}
baseDict = {'b_key':OrderedDict([('Read_PMax', [3325]), ('Max_Read_P50', [70]), ('Avg_Read_P50', [70]), ('Max_Read_P90', [136]), ('Avg_Read_P90', [136])])}

for key in currentDict:
 x = currentDict[key]
for key in baseDict:
 y = baseDict[key]
z = {}
w = {}
for i, (key, value) in enumerate(x.items()):
    z[key]=value
for j,(key, value) in enumerate(y.items()):
    w[key]=value
result_dict = {}
result_ordered_dict = OrderedDict(result_dict)
for key in z.keys():
    if key in w:
        result_ordered_dict[key] = [str(round(((z[key][i] - w[key][i])/w[key][i])*100,2))+'%' for i in range(len(z[key]))]
print(result_ordered_dict)

Output:

OrderedDict([('Read_PMax', ['545.92%']), ('Max_Read_P50', ['31.43%']), ('Avg_Read_P50', ['31.43%']), ('Max_Read_P90', ['44.85%']), ('Avg_Read_P90', ['44.85%'])])