Skip to content

Instantly share code, notes, and snippets.

@rcook
Created March 13, 2022 16:49
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 rcook/554d386a103e59abbe2559e6c504a530 to your computer and use it in GitHub Desktop.
Save rcook/554d386a103e59abbe2559e6c504a530 to your computer and use it in GitHub Desktop.
Compare dictionaries in Python
def dump_diffs(x, y, parts):
path = "/".join(parts)
if x is None:
if y is None:
pass
else:
print(f"{path}: x value {x} does not match y value {y}")
elif isinstance(x, int):
if isinstance(y, int):
if x == y:
pass
else:
print(f"{path}: x value {x} does not match y value {y}")
else:
print(f"{path}: y is not an int")
elif isinstance(x, str):
if isinstance(y, str):
if x == y:
pass
else:
print(f"{path}: x value {x} does not match y value {y}")
else:
print(f"{path}: y is not a str")
elif isinstance(x, list):
if isinstance(y, list):
x_count = len(x)
y_count = len(y)
if x_count == y_count:
for i in range(0, x_count):
dump_diffs(x[i], y[i], parts=parts + [f"[{i}]"])
else:
print(f"{path}: x count {x_count} does not match y count {y_count}")
pass
else:
print(f"{path}: y is not a list")
else:
for x_k, x_v in x.items():
if x_k not in y:
print(f"{path}: {x_k} missing from y")
else:
y_v = y[x_k]
dump_diffs(x_v, y_v, parts=parts + [x_k])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment