[Python-Dev] Guarantee ordered dict literals in v3.7?
Steven D'Aprano
steve at pearwood.info
Wed Dec 20 03:43:19 EST 2017
On Tue, Dec 19, 2017 at 04:56:16PM -0800, Steve Dower wrote:
> On 19Dec2017 1004, Chris Barker wrote:
> >(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.
Indeed. Regular dicts preserve insertion order, they don't take
insertion order into account for the purposes of equality. See the
example here:
https://docs.python.org/3.7/library/stdtypes.html#mapping-types-dict
and the description of mapping equality:
https://docs.python.org/3.7/reference/expressions.html#value-comparisons
"Mappings (instances of dict) compare equal if and only if they
have equal (key, value) pairs. Equality comparison of the keys
and values enforces reflexivity."
Changing that would be a *huge* backwards-compatibility breaking change.
Aside: I've just noticed that mapping equality is not transitive:
a == b and b == c does not imply that a == c.
py> from collections import OrderedDict as OD
py> a, b, c = OD.fromkeys('xyz'), dict.fromkeys('xyz'), OD.fromkeys('zyx'))
py> a == b == c
True
py> a == c
False
--
Steve
More information about the Python-Dev
mailing list