Jono
Jono

Reputation: 705

Elegant comparison of elements in two dictionaries within tolerance in python

Lets say I have these two dictionaries:

d1 = {'a' : 1.001, 'b' : 2.0002, 'c' : 3}
d2 = {'a' : 1.002, 'b' : 2,      'c' : 3, 'd' : 4}

What is the most elegant way of comparing them to some tolerance?

Currently I have:

TOL = 0.001
different = False

for key in d1.keys():
    if abs(d1[key] - d2[key]) > TOL:
        different = True
        print "|{} - {}| > {}".format(d1[key], d2[key], TOL)
        break

But it feels a bit hacky.

Upvotes: 0

Views: 652

Answers (1)

Steinar Lima
Steinar Lima

Reputation: 7821

I don't think your solution is too bad, but I would've looped over the intersection of d1 and d2's keys to avoid KeyErrors. A lambda function may sweeten things a bit too.

d1 = {'a' : 1.001, 'b' : 2.0002, 'c' : 3}
d2 = {'a' : 1.002, 'b' : 2,      'c' : 3, 'd' : 4}
tol = 0.001
equals = lambda a, b: abs(a-b) < tol

# For loop with print
for key in set(d1.keys()) & set(d2.keys()):
    print '{} == {} is {} (tolerance: {})'.format(
        d1[key], d2[key], equals(d1[key], d2[key]), tol
    )

# 1.001 == 1.002 is False (tolerance: 0.001)
# 3 == 3 is True (tolerance: 0.001)
# 2.0002 == 2 is True (tolerance: 0.001)

# List comprehension with bools
print [equals(d1[key], d2[key]) for key in set(d1.keys()) & set(d2.keys())]

# [False, True, True]

Upvotes: 1

Related Questions