对 Python 中具有相同键的两个字典中的值执行数学运算

Performing mathematical operations on values from two dictionaries with same keys in Python

我有两个字典,比方说,a = {'A':{2021:45.65},'B':{2021:56.34}}b = {'A':{2021:78.67},'B':{2021:87.54}}

我想从 A 和 B 中获取值 'sub-dictionaries' 并计算第二个字典中的值与第一个字典中的值的百分比。

我似乎想不出一种方法来访问不同字典中的浮点值并计算结果。

-------------------------更新-------- --------------

抱歉没有正确理解我的问题。我想出了一个方法来做到这一点,如果你认为它仍然有问题,请提及。

dict_keys = ['A','B']
for x in dict_keys:
   val1 = a[x].values()
   val2 = b[x].values()

正如一些评论中提到的那样,将其分解成逻辑 parts/steps 会有很大帮助。

//pseudocode
if the len of a == len of b:
    for key, value in a:
        if the len of a[key] == len of b[key]:
            for key, value in a[key]:
                more_less = a's key's value divided by b's key's value

适用于在此处使用谷歌搜索的任何人的正确代码:

#  [partially] confirming data integrity - you can do more here if needed
lf len(a) == len(b):
    #  iterate through each dictionary in `a` to compare to the associated dictionary in `b`
    for key, value in a:
        #  [partially] confirming data integrity of the 'child' dictionaries
        if len(value) == len(b[key]):
            for key2, value2 in a[key]:
                #  key2 is, in this case, '2021'; value2 is the number
                more_less = value2 / b[key][key2]
                #  We'll print the result here, you can also use string formatting, of course, but to keep it as the most basic level:
                print(str(b[key][key2]) + " is " + str(more_less) + "% of " + value2 + ".")

如果你保证 a 和 b 的字典结构完全相同,你可以简单地遍历一个并使用密钥访问另一个,但这是一种相当薄弱的方法。

result = {}  
for key, item in a.items():  
    for nest_key, nest_item in a[key].items():
        result[key] = nest_item / b[key][nest_key]