Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm writing a doctest for a function that outputs a dictionary. The doctest looks like

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

When I run it, it fails with

Expected:
    {'this': 'is', 'a': 'dictionary'}
Got:
    {'a': 'dictionary', 'this': 'is'}

My best guess as to the cause of this failure is that doctest isn't checking dictionary equality, but __repr__ equality. This post indicates that there's some way to trick doctest into checking dictionary equality. How can I do this?

question from:https://stackoverflow.com/questions/15549429/how-do-i-test-dictionary-equality-with-pythons-doctest-package

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
180 views
Welcome To Ask or Share your Answers For Others

1 Answer

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())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...