Getting the difference (in values) between two dictionaries in python
Solution 1
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.
Solution 2
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}
Solution 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}
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
Related videos on Youtube
celeminus
Updated on September 16, 2022Comments
-
celeminus over 1 year
Let's say you are given 2 dictionaries,
A
andB
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 ifx
is the value from key"A"
andy
is the value from key"B"
then result should bex-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).