[IPython-dev] display of dicts?

Chris Barker chris.barker at noaa.gov
Tue Dec 19 12:24:24 EST 2017


On Tue, Dec 19, 2017 at 7:45 AM, Thomas Kluyver <takowl at gmail.com> wrote:

> I think there's less danger of us breaking someone's *code* that relies on
> dictionary presentation. But it's more important for us to think about
> what's useful for human interpretation, since IPython is all about the
> interface.
>

exactly.


> I disagree with that. Consistency is part of it, but I think the sorting
>> is often helpful in itself. It's much easier to see if the dictionary has a
>> key 'foo' if it's shown in alphabetical order than if it's not.
>>
>
> The new dict also only gives you consistency if the data going into it is
> consistently ordered. If you are building a dictionary of filenames with
> os.listdir(), for example, order is not guaranteed.
>

but whether default sort order of the keys is meaningful is a happy
coincidence -- if the keys happen to be strings for which alphabetization
makes sense, then great. If they are anything else, then not so great.

Granted, string keys where alphabetization makes sense are pretty darn
common, but still a "special case"

In fact, I discovered this with this example, which I used in my intro to
Python class to demonstrate dict's arbitrary order:

In python 2.7:


In [*1*]: d = {"one": 1, "two": 2, "three": 3}


In [*2*]: d

Out[*2*]: {'one': 1, 'three': 3, 'two': 2}


In [*3*]: d.keys()

Out[*3*]: ['three', 'two', 'one']

Interesting that the display version is different than the d.keys() version
-- but I just thought that was a nice demo of "dicts are arbitrary order"

Then, in Python3.6, which I am now using for teaching:

In [*1*]: d = {"one": 1, "two": 2, "three": 3}


In [*2*]: d

Out[*2*]: {'one': 1, 'three': 3, 'two': 2}


In [*3*]: d.keys()

Out[*3*]: dict_keys(['one', 'two', 'three'])


In [*4*]: print(d)

{'one': 1, 'two': 2, 'three': 3}

Huh? d.keys() is preserving order, print is preserving order, but plain
display is not. it took me some time to realize that the display order was
alphabetical, and then I figured that iPython must be sorting them, which
then led me to the fact that the stdlib pprint sorts them too.

I have been suing iPython for many years, and had never noticed that
display used something other than "str" or "repr", nor that pprint sorted
dicts.

Still not sure if we should change it, but I don't think sorting dicts
based on default sort of keys is an obviously "best" way to present a dict.

-Chris


-- 

Christopher Barker, Ph.D.
Oceanographer

Emergency Response Division
NOAA/NOS/OR&R            (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception

Chris.Barker at noaa.gov
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/ipython-dev/attachments/20171219/e81a2c17/attachment.html>


More information about the IPython-dev mailing list