Created
December 7, 2012 21:09
-
-
Save durden/4236551 to your computer and use it in GitHub Desktop.
Compare dicts with fuzzy float comparison
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def fuzzyDictEqual(d1, d2, precision): | |
""" | |
Compare two dicts recursively (just as standard '==' except floating point | |
values are compared within given precision. | |
""" | |
if len(d1) != len(d2): | |
return False | |
for k, v in d1.iteritems(): | |
# Make sure all the keys are equal | |
if k not in d2: | |
return False | |
# Fuzzy float comparison | |
if isinstance(v, float) and isinstance(d2[k], float): | |
if not abs(v - d2[k]) < precision: | |
return False | |
# Recursive compare if there are nested dicts | |
elif isinstance(v, dict): | |
if not fuzzyDictEqual(v, d2[k], precision): | |
return False | |
# Fall back to default | |
elif v != d2[k]: | |
return False | |
return True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Works well!
For future readers of this gist:
With Python3 change
d1.iteritems()
tod1.items()
on line 10.And to handle NaN cases, add this after line 16, inside the
isinstance(v, float)....
block (and importingmath
):