The code is:
from pprint import pprint
d = {"b" : "Maria", "c" : "Helen", "a" : "George"}
pprint(d, width = 1)
The output is:
{'a': 'George',
'b': 'Maria',
'c': 'Helen'}
But, the desired output is:
{'b': 'Maria',
'c': 'Helen',
'a': 'George'}
Could this be done with pprint or is there another way?
Using pprintThe Python pprint module actually already sorts dictionaries by key. The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter.
It is not sorting. dict is not ordered at all, so you cannot influence the key order in any way.
The pprint module in Python is a utility module that you can use to print data structures in a readable, pretty way. It's a part of the standard library that's especially useful for debugging code dealing with API requests, large JSON files, and data in general.
You can use sort_dicts=False
to prevent it from sorting them alphabetically:
pprint.pprint(data, sort_dicts=False)
Since Python 3.7 (or 3.6 in the case of cPython), dict
preserves insertion order. For any version prior, you will need to use an OrderedDict
to keep keys in order.
Although, from the doc on pprint
:
Dictionaries are sorted by key before the display is computed.
This means pprint
will break your desired order regardless.
You can also use json.dumps
to pretty print your data.
Code:
import json
from collections import OrderedDict
# For Python 3.6 and prior, use an OrderedDict
d = OrderedDict(b="Maria", c="Helen", a="George")
print(json.dumps(d, indent=1))
Output:
{
"b": "Maria",
"c": "Helen",
"a": "George"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With