Recent versions of pprint
support the sort_dicts
argument (defaults to True
for backward compatibility):
>>> from pprint import pprint
>>> d = {"foo": "bar", "baz": "quux"}
>>> pprint(d)
{'baz': 'quux', 'foo': 'bar'}
>>> pprint(d, sort_dicts=False)
{'foo': 'bar', 'baz': 'quux'}
Older versions do not have this because it was based around the fact that dictionaries are unordered in older python versions, so it would sort the keys alphabetically given that the order was arbitrary anyway. In python >= 3.7, dictionaries are in insertion order, so this is the order obtained with sort_dicts=False
.
There was unfortunately a lag of one python version between when dictionaries were ordered and when pprint
caught up with this fact. Here is the above repeated but in Python 3.7:
>>> from pprint import pprint
>>> d = {"foo": "bar", "baz": "quux"}
>>> pprint(d, sort_dicts=False)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: pprint() got an unexpected keyword argument 'sort_dicts'