Created
June 24, 2026 15:33
-
-
Save lucasbracher/82fdef130af12a46e1c078ab9cc13f8b to your computer and use it in GitHub Desktop.
Difference between 2 dicts
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 diff_dicts( | |
| d1: dict, | |
| d2: dict, | |
| path: str = "" | |
| ) -> list[str]: | |
| diffs = [] | |
| keys = set(d1.keys()) | set(d2.keys()) | |
| for key in keys: | |
| current_path = f"{path}.{key}" if path else str(key) | |
| if key not in d1: | |
| diffs.append( | |
| f"Keys missing in first dict: {current_path}" | |
| ) | |
| continue | |
| if key not in d2: | |
| diffs.append( | |
| f"Keys missing in second dict: {current_path}" | |
| ) | |
| continue | |
| v1 = d1[key] | |
| v2 = d2[key] | |
| # Nested dict | |
| if isinstance(v1, dict) and isinstance(v2, dict): | |
| diffs.extend( | |
| diff_dicts(v1, v2, current_path) | |
| ) | |
| # List | |
| elif isinstance(v1, list) and isinstance(v2, list): | |
| if len(v1) != len(v2): | |
| diffs.append( | |
| f"Different length in {current_path}: " | |
| f"{len(v1)} != {len(v2)}" | |
| ) | |
| continue | |
| for index, (item1, item2) in enumerate(zip(v1, v2)): | |
| item_path = f"{current_path}[{index}]" | |
| if isinstance(item1, dict) and isinstance(item2, dict): | |
| diffs.extend( | |
| diff_dicts(item1, item2, item_path) | |
| ) | |
| elif item1 != item2: | |
| diffs.append( | |
| f"Different value in {item_path}: " | |
| f"{item1!r} != {item2!r}" | |
| ) | |
| # Simple value | |
| elif v1 != v2: | |
| diffs.append( | |
| f"Different value in {current_path}: " | |
| f"{v1!r} != {v2!r}" | |
| ) | |
| return diffs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment