[Python-Dev] Guarantee ordered dict literals in v3.7?

Steve Dower steve.dower at python.org
Tue Dec 19 19:56:16 EST 2017


On 19Dec2017 1004, Chris Barker wrote:
> Nathaniel Smith has pointed out that eval(pprint(a_dict)) is supposed to 
> return the same dict -- so documented behavior may already be broken.

Two relevant quotes from the pprint module docs:

 >>> 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

 >>> Dictionaries are sorted by key before the display is computed.

It says nothing about the resulting dict being the same as the original 
one, just that it can be used as input. So these are both still true 
(until someone deliberately breaks the latter). In any case, there are 
so many ways to spoil the first point for yourself that it's hardly 
worth treating as an important constraint.

> (though I assume order is still ignored when comparing dicts, so: 
> eval(pprint(a_dict)) == a_dict will still hold.

Order had better be ignored when comparing dicts, or plenty of code will 
break. For example:

 >>> {'a': 1, 'b': 2} == {'b': 2, 'a': 1}
True

Saying that "iter(dict)" will produce keys in the same order as they 
were inserted is not the same as saying that "dict" is an ordered 
mapping. As far as I understand, we've only said the first part.

(And the "nerve" here is that I disagreed with even the first part, but 
didn't fight it too strongly because I never relied on the iteration 
order of dict. However, I *do* rely on nobody else relying on the 
iteration order of dict either, and so proposals to change existing 
semantics that were previously independent of insertion order to make 
them rely on insertion order will affect me. So now I'm pushing back.)

Cheers,
Steve


More information about the Python-Dev mailing list