Skip to content

Instantly share code, notes, and snippets.

@xfenix
Last active December 28, 2023 06:08
Show Gist options
  • Save xfenix/b93a694a1f50686d206df6e46af2b5ba to your computer and use it in GitHub Desktop.
Save xfenix/b93a694a1f50686d206df6e46af2b5ba to your computer and use it in GitHub Desktop.
Diff dict function
def compare_dicts(old_dict, new_dict):
diff_items = {}
for key, value in old_dict.items():
if isinstance(value, dict):
result = compare_dicts(value,
new_dict[key] if key in new_dict and isinstance(new_dict[key], dict) else {})
diff_items.update(
{'{}.{}'.format(key, sub_key): value for sub_key, value in result.items()})
elif key not in new_dict or value != new_dict[key]:
diff_items[key] = value
return diff_items
def format_one_dict(prefix, dict_data):
return '\n'.join(['{} {} {}'.format(prefix, key, value) for key, value in dict_data.items()])
def repr_diff_dict(old_dict, new_dict):
return '{}\n{}'.format(format_one_dict('-', old_dict), format_one_dict('+', new_dict))
def diff_dict(old_dict, new_dict):
return repr_diff_dict(compare_dicts(old_dict, new_dict), compare_dicts(new_dict, old_dict))
# Usage
# >>> old_dict = {'a': 10, 'c': {'x': 11, 'z': {'e': 20}}, 'b': 15}
# >>> new_dict = {'e': 30, 'c': 66}
# >>> print(diff_dict(old_dict, new_dict))
# - a 10
# - c.x 11
# - c.z.e 20
# - b 15
# + e 30
# + c 66
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment