Created
August 2, 2023 14:42
-
-
Save e-dreyer/5cc62448cb58400399804d3b72756001 to your computer and use it in GitHub Desktop.
Deep comparison of dictionaries using zip
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 deep_compare_dicts(dict1, dict2): | |
if len(dict1) != len(dict2): | |
return False | |
for (key1, value1), (key2, value2) in zip(dict1.items(), dict2.items()): | |
if key1 != key2: | |
return False | |
if isinstance(value1, dict) and isinstance(value2, dict): | |
if not deep_compare_dicts(value1, value2): | |
return False | |
else: | |
if value1 != value2: | |
return False | |
return True | |
# Test dictionaries | |
dict1 = {'a': 1, 'b': {'x': 2, 'y': 3}, 'c': [4, 5, 6]} | |
dict2 = {'a': 1, 'b': {'x': 2, 'y': 3}, 'c': [4, 5, 6]} | |
dict3 = {'a': 1, 'b': {'x': 2, 'y': 4}, 'c': [4, 5, 6]} | |
print(deep_compare_dicts(dict1, dict2)) # Output: True (dict1 and dict2 are equal) | |
print(deep_compare_dicts(dict1, dict3)) # Output: False (dict1 and dict3 are not equal) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment