Skip to content

Instantly share code, notes, and snippets.

@sprin
Last active May 20, 2018 18:28
Show Gist options
  • Save sprin/6034947 to your computer and use it in GitHub Desktop.
Save sprin/6034947 to your computer and use it in GitHub Desktop.
Functions for pretty-printing dictionary differences, including an assert function for testing dictionary equality (Python)
"""
Functions for pretty-printing dictionary differences, including an
assert function for testing purposes.
Under MIT License from sprin. (https://gist.github.com/sprin/6034947/)
Example:
a = {
'key1': 'val1',
'key2': 'val2',
'key3': 'val3',
'key4': 'val4',
}
b = {
'key3': 'val3',
'key4': [],
'key5': 5,
'key6': {}
}
assert_dict_eq(a, b)
# prints...
Traceback (most recent call last):
...
AssertionError: Dictionaries not equal. Differing key-values:
a | b
'key2': 'val2' |
'key1': 'val1' |
'key4': 'val4' | 'key4': []
| 'key6': {}
| 'key5': 5
"""
import sys
def format_dict_pair(seq, just):
"""
Format a pair of single key-value dicts in a list, with right
justification applied to the first dict, given by the `just` arg.
"""
def format_single_element_dict(dict_):
"""Inner helper function to format single key-value dicts."""
if dict_:
k, v = dict_.items()[0]
return "{0}: {1}".format(repr(k), repr(v))
else:
return ''
return (
format_single_element_dict(seq[0]).rjust(just, ' ')
+ ' | ' + format_single_element_dict(seq[1]))
def format_dict_differences(differences):
"""Pretty-format a list of dictionary differences."""
# Find longest first element, for header formatting purporses.
def get_first_dict_len(x):
return len(str(x[0]))
maxlen = max(map(get_first_dict_len, differences))
header = ' ' * (maxlen - 1) + 'a | b\n'
# Show differences on separate lines, justified and separated by pipe.
body = "\n".join([format_dict_pair(seq, maxlen) for seq in differences])
return header + body + '\n'
def get_dict_differences(a, b):
"""
Get the differences between two dictionaries as a list of pairs of
single key-value dicts.
"""
dict_differences = []
for a_key, a_value in a.iteritems():
try:
b_value = b[a_key]
if a_value != b_value:
dict_differences.append([{a_key: a_value}, {a_key: b_value}])
except KeyError:
dict_differences.append([{a_key: a_value}, {}])
for b_key, b_value in b.iteritems():
try:
a[b_key]
except KeyError:
dict_differences.append([{}, {b_key: b_value}])
return dict_differences
def assert_dict_eq(a, b):
"""
Assert that a has the same keys and values as b, and pretty-print
the differences if any.
"""
dict_differences = get_dict_differences(a, b)
try:
assert dict_differences == []
except AssertionError as e:
diff_str = format_dict_differences(dict_differences)
new_msg = (
e.message
+ 'Dictionaries not equal. Differing key-values:\n\n'
+ diff_str)
raise type(e), type(e)(new_msg), sys.exc_info()[2]
@sprin
Copy link
Author

sprin commented Jul 19, 2013

MIT LICENSE

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment