How do I test dictionary-equality with Python's doctest-package? How do I test dictionary-equality with Python's doctest-package? python python

How do I test dictionary-equality with Python's doctest-package?


Another good way is to use pprint (in the standard library).

>>> import pprint>>> pprint.pprint({"second": 1, "first": 0}){'first': 0, 'second': 1}

According to its source code, it's sorting dicts for you:

http://hg.python.org/cpython/file/2.7/Lib/pprint.py#l158

items = _sorted(object.items())


Doctest doesn't check __repr__ equality, per se, it just checks that the output is exactly the same. You have to ensure that whatever is printed will be the same for the same dictionary. You can do that with this one-liner:

>>> sorted(my_function().items())[('a', 'dictionary'), ('this', 'is')]

Although this variation on your solution might be cleaner:

>>> my_function() == {'this': 'is', 'a': 'dictionary'}True


I ended up using this. Hacky, but it works.

>>> p = my_function()>>> {'this': 'is', 'a': 'dictionary'} == pTrue