If you read the source of pprint.py
you'll find that in PrettyPrinter._pprint_dict()
, the method responsible for formatting dicts:
def _pprint_dict(self, object, stream, indent, allowance, context, level):
write = stream.write
write('{')
if self._indent_per_level > 1:
write((self._indent_per_level - 1) * ' ')
length = len(object)
if length:
items = sorted(object.items(), key=_safe_tuple)
self._format_dict_items(items, stream, indent, allowance + 1,
context, level)
write('}')
_dispatch[dict.__repr__] = _pprint_dict
There's this line items = sorted(object.items(), key=_safe_tuple)
, so dict items are always sorted first before being processed for formatting, and you will have to override it yourself by copying and pasting it and removing the offending line in your own script:
import pprint as pp
def _pprint_dict(self, object, stream, indent, allowance, context, level):
write = stream.write
write('{')
if self._indent_per_level > 1:
write((self._indent_per_level - 1) * ' ')
length = len(object)
if length:
self._format_dict_items(object.items(), stream, indent, allowance + 1,
context, level)
write('}')
pp.PrettyPrinter._dispatch[dict.__repr__] = _pprint_dict
so that:
pp.pprint({"b" : "Maria", "c" : "Helen", "a" : "George"}, width=1)
will output (in Python 3.6+):
{'b': 'Maria',
'c': 'Helen',
'a': 'George'}
OrderedDict
or use a function to sort over keys and print them individually. But as another note, why do you care if a dictionary has an order? – PrefermentOrderedDict([items go here])
. Doesn't look much like the desired output. – Arboreouspprint
so the OP needs to consider a different metho – TerynPrettyPrinter
and overridepformat
to get your desired output. I'm not sure though – Gripper