How to print sorted dictionary with pprint function

854 Views Asked by At

I have a simple dictionary (old_d) in the form of {'stringkey': intvalue, ...} and I want to order it by value. To do that I use.

new_d = {k: v for k, v in sorted(old_d.items(), key=lambda x: x[1])}

If I use print(new_d) this works, but when I use pprint(new_d) it returns me the dictionary ordered by key name and not by value. I would like to use pprint because these dictionaries have a lot of objects and the output cant't be on one line, how can I do that?

2

There are 2 best solutions below

0
On

pprint() has a keyword argument sort_dicts which solves your problem, but it is only available since python 3.8 version.

0
On

Recent versions of pprint support the sort_dicts argument (defaults to True for backward compatibility):

>>> from pprint import pprint
>>> d = {"foo": "bar", "baz": "quux"}
>>> pprint(d)
{'baz': 'quux', 'foo': 'bar'}
>>> pprint(d, sort_dicts=False)
{'foo': 'bar', 'baz': 'quux'}

Older versions do not have this because it was based around the fact that dictionaries are unordered in older python versions, so it would sort the keys alphabetically given that the order was arbitrary anyway. In python >= 3.7, dictionaries are in insertion order, so this is the order obtained with sort_dicts=False.

There was unfortunately a lag of one python version between when dictionaries were ordered and when pprint caught up with this fact. Here is the above repeated but in Python 3.7:

>>> from pprint import pprint
>>> d = {"foo": "bar", "baz": "quux"}
>>> pprint(d, sort_dicts=False)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: pprint() got an unexpected keyword argument 'sort_dicts'