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

Time:04-28

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()

CodePudding user response:

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

Write it out, if you get an error, post it and I will post help / more code. I will also edit this with proper code after OP gets this figured out, so please don't downvote this in the meantime. I am doing this for OP and will make an evergreen version for anyone reading this down the line. Thanks.

--------------------------UPDATE------------------------

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   ".")

CodePudding user response:

if you guarantee the structure of the dicts are exactly the same for a and b you can simply traverse one and use the key to access the other, but this is rather weak of an approach.

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