Skip to content

Instantly share code, notes, and snippets.

@durden
Created December 7, 2012 21:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save durden/4236551 to your computer and use it in GitHub Desktop.
Save durden/4236551 to your computer and use it in GitHub Desktop.
Compare dicts with fuzzy float comparison
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
@vaimo-wilko
Copy link

Works well!

For future readers of this gist:

  • With Python3 change d1.iteritems() to d1.items() on line 10.

  • And to handle NaN cases, add this after line 16, inside the isinstance(v, float).... block (and importing math):

    if math.isnan(v) and math.isnan(d2[k]):
        continue

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment