如何在 Python 中的两个有序字典之间进行算术运算?请帮助我

问题描述 投票:0回答:1

我正在尝试在 Python 中的两个有序字典之间进行算术运算。但是我遇到了错误:“TypeError:不支持的操作数类型 -:'collections.OrderedDict' 和 'int'”

下面是python代码:

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 : 最终结果应该赋值给test_dict。在这里,我们想要找到上面提供的每个字典 (a, b) 的“Max_Value”之间的百分比差异。与“Min_Value”类似。 'Max_Value' 和 'Min_Value' 都在字典 a、b 的 OrderedDict 中。

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

但是,我面临错误:“TypeError:不支持的操作数类型 -:'collections.OrderedDict' 和 'int'”

我请求你真诚的帮助解决这个问题。

python-3.x list dictionary tuples ordereddictionary
1个回答
0
投票

经过长期的努力,我自己找到了想要的解决方案,继续探索。下面是代码:

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%'])])
© www.soinside.com 2019 - 2024. All rights reserved.