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

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

Ideally, you can also compare the gain in percent (how many values ​​changed in percent between two dictionaries, which are snapshots of numbers at a specific time).

+4
source share
4 answers

For two dictionaries Aand 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 keys that are the same in the words of both .

+5
source

You can use comprehension dictto scroll through the keys, and 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 that both dicthave the same keys. Otherwise, you will have to think about what behavior you expect if there are keys in one dict, but not in the other (maybe some default value?)

, ,

>>> {k: b[k] - a[k] for k in a.keys() & b.keys()}
{'a': -4, 'b': 4, 'c': 7}
+3
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}

, ...

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
+2

If you want to get the difference of similar keys in a new dictionary, you can 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 enter on one line

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

Source: https://habr.com/ru/post/1674669/


All Articles