Skip to content
Advertisement

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

I have two dictionaries named as, lets say, a = {'A':{2021:45.65},'B':{2021:56.34}} and b = {'A':{2021:78.67},'B':{2021:87.54}}

I want to get the values from both A and B ‘sub-dictionaries’ and compute what percentage of value from the second dictionary is the value from the first dictionary.

I can’t seem to figure out a way how to access both the float values from different dictionaries and compute the result.

————————–UPDATE————————

Apologies about not comprehending my problem in a proper manner. I figured out a way to do that and if you think it has an issue still please do mention.

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

Advertisement

Answer

As has been mentioned in some of the comments breaking this into logical parts/steps can help a lot.

//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

Proper code for anyone Googling their way here:

#  [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 + ".")
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement