pythondictionarypretty-printpprint

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?


Solution

  • 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"
    }