Created
March 13, 2022 16:49
-
-
Save rcook/554d386a103e59abbe2559e6c504a530 to your computer and use it in GitHub Desktop.
Compare dictionaries in Python
This file contains hidden or 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 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