Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the difference (in values) between two dictionaries in python

Let's say you are given 2 dictionaries, A and B with keys that can be the same but values (integers) that will be different. How can you compare the 2 dictionaries so that if the key matches you get the difference (eg if x is the value from key "A" and y is the value from key "B" then result should be x-y) between the 2 dictionaries as a result (preferably as a new dictionary).

Ideally you'd also be able to compare the gain in percent (how much the values changed percentage-wise between the 2 dictionaries which are snapshots of numbers at a specific time).

like image 260
celeminus Avatar asked Apr 12 '17 14:04

celeminus


1 Answers

def difference_dict(Dict_A, Dict_B):
    output_dict = {}
    for key in Dict_A.keys():
        if key in Dict_B.keys():
            output_dict[key] = abs(Dict_A[key] - Dict_B[key])
    return output_dict

>>> Dict_A = {'a': 4, 'b': 3, 'c':7}
>>> Dict_B = {'a': 3, 'c': 23, 'd': 2}
>>> Diff = difference_dict(Dict_A, Dict_B)
>>> Diff
{'a': 1, 'c': 16}

If you wanted to fit that all onto one line, it would be...

def difference_dict(Dict_A, Dict_B):
    output_dict = {key: abs(Dict_A[key] - Dict_B[key]) for key in Dict_A.keys() if key in Dict_B.keys()}
    return output_dict
like image 63
slearner Avatar answered Sep 27 '22 21:09

slearner