Please help on this sorted function

Chris Angelico rosuav at gmail.com
Tue Jun 2 20:01:36 EDT 2015


On Wed, Jun 3, 2015 at 6:25 AM, fl <rxjwg98 at gmail.com> wrote:
> I am still new to Python. How to get the sorted dictionary output:
>
> {1: 'D', 2: 'B', 3: 'A', 4: 'E', 5: 'B'}

Since dictionaries don't actually have any sort of order to them, the
best thing to do is usually to simply display it in order. And there's
a very handy function for doing that: a pretty-printer.

>>> import pprint
>>> pprint.pprint({1: 'D', 2: 'B', 5: 'B', 4: 'E', 3: 'A'})
{1: 'D', 2: 'B', 3: 'A', 4: 'E', 5: 'B'}

This one comes with Python, so you can use it as easily as that above
example. Or you could do it this way:

>>> from pprint import pprint
>>> pprint({1: 'D', 2: 'B', 5: 'B', 4: 'E', 3: 'A'})
{1: 'D', 2: 'B', 3: 'A', 4: 'E', 5: 'B'}

For a lot of Python data structures, this will give you a tidy and
human-readable display.

ChrisA



More information about the Python-list mailing list