celeminus
celeminus

Reputation: 101

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

Upvotes: 10

Views: 24697

Answers (5)

Anaderi
Anaderi

Reputation: 791

here is a python package for this case:

https://dictdiffer.readthedocs.io/en/latest/

from dictdiffer import diff
print(list(diff(a, b)))

would do the trick.

Upvotes: 0

slearner
slearner

Reputation: 672

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

Upvotes: 3

Kind Stranger
Kind Stranger

Reputation: 1761

If you want to get the difference of similar keys into a new dictionary, you could do something like the following:

new_dict={}
for key in A:
    if key in B:
        new_dict[key] = A[key] - B[key]

...which we can fit into one line

new_dict = { key : A[key] - B[key] for key in A if key in B }

Upvotes: 0

Wright
Wright

Reputation: 3424

Given two dictionaries, A and B which may/may not have the same keys, you can do this:

A = {'a':5, 't':4, 'd':2}
B = {'s':11, 'a':4, 'd': 0}

C = {x: A[x] - B[x] for x in A if x in B}

Which only subtracts the keys that are the same in both dictionaries.

Upvotes: 7

Cory Kramer
Cory Kramer

Reputation: 117876

You could use a dict comprehension to loop through the keys, then subtract the corresponding values from each original dict.

>>> a = {'a': 5, 'b': 3, 'c': 12}
>>> b = {'a': 1, 'b': 7, 'c': 19}
>>> {k: b[k] - a[k] for k in a}
{'a': -4, 'b': 4, 'c': 7}

This assumes both dict have the exact same keys. Otherwise you'd have to think about what behavior you expect if there are keys in one dict but not the other (maybe some default value?)

Otherwise if you want to evaluate only shared keys, you can use the set intersection of the keys

>>> {k: b[k] - a[k] for k in a.keys() & b.keys()}
{'a': -4, 'b': 4, 'c': 7}

Upvotes: 5

Related Questions