Home > front end >  subtract values of two python dictionaries with the same key
subtract values of two python dictionaries with the same key

Time:04-05

I have a couple of python dictionaries

dict1 = {0:[('a',10),('b',11),('c',12)],1:[('a',12),('b',15),('c',16)]}
dict2 = {0:[('a',13),('b',15),('c',12)],1:[('a',12),('b',18),('c',20)]}

and I'm trying to see if there is an increment in the value of the tuple.

i.e dict1 (a,10) dict2 (a,13), so there's been an increment of 3. The resultant

Expected output:

dict3 = {0: ('a',3),('b',4),1:('b',3),('c',4)}

My code


dict3 = {}
for (k,v), (k2,v2) in zip(dict1.items(),dict2.items()):
    for va1,va2 in zip(v,v2):
        if abs(int(va1[1])-int(va2[1]) !=0):
            dict3[k] = ((va1[0],abs(int(va1[1])-int(va2[1]))))

however is getting overwritten

{0: ('b', 4), 1: ('c', 4)}

CodePudding user response:

In dict3[k] = ((va1[0],abs(int(va1[1])-int(va2[1])))) you override the value every iteration, you need to add the new value to the existing instead. You can do it using get with an empty list as default value

diff = abs(int(va1[1]) - int(va2[1]))
if diff != 0:
    dict3[k] = dict3.get(k, [])   [(va1[0], diff)]

Output:

{0: [('a', 3), ('b', 4)], 1: [('b', 3), ('c', 4)]}

CodePudding user response:

You forgot to create the list structure in your output, so you just overwrite the dict3 value with each new element instead of creating a new item in a list.

Here is an alternative using a dictionary comprehension

dict1 = {0:[('a',10),('b',11),('c',12)],1:[('a',12),('b',15),('c',16)]}
dict2 = {0:[('a',13),('b',15),('c',12)],1:[('a',12),('b',18),('c',20)]}

out = {k: [(a, abs(b2-b)) for i, (a ,b) in enumerate(l)
           if (b2:=dict2[k][i][1]) != b]  # walrus operator (python ≥ 3.8)
       for k,l in dict1.items()}

output:

{0: [('a', 3), ('b', 4)], 1: [('b', 3), ('c', 4)]}
  • Related