Ever since Python 3.7, Python guarantees that keys in a dictionary will retain their insertion order. (They still don’t behave exactly the same as OrderedDict
objects, though, as two dicts a
and b
can be considered equal a == b
even if the order of the keys is different, whereas OrderedDict
does check this upon testing for equality.)
Python 3.8 or newer:
You can use sort_dicts=False
to prevent it from sorting them alphabetically:
>>> example_dict = {'x': 1, 'b': 2, 'm': 3}
>>> import pprint
>>> pprint.pprint(example_dict, sort_dicts=False)
{'x': 1, 'b': 2, 'm': 3}
Python 3.7 or older:
As a temporary workaround, you can try dumping in JSON format instead of using pprint
.
You lose some type information, but it looks nice and keeps the order.
>>> import json
>>> print(json.dumps(example_dict, indent=4))
{
"x": 1,
"b": 2,
"m": 3
}