Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I avoid a sorted dictionary output after I've used pprint.pprint, in Python?

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?

like image 709
Maria Pantsiou Avatar asked Aug 10 '18 14:08

Maria Pantsiou


People also ask

Does Pprint sort?

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.

Is dictionary automatically sorted in Python?

It is not sorting. dict is not ordered at all, so you cannot influence the key order in any way.

What is Pprint Pprint in Python?

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.


1 Answers

Python 3.8 or newer:

You can use sort_dicts=False to prevent it from sorting them alphabetically:

pprint.pprint(data, sort_dicts=False)

Python 3.7 or older:

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.

Alternative method:

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"
}
like image 157
Olivier Melançon Avatar answered Sep 20 '22 11:09

Olivier Melançon