Why does the OrderedDict
keys view compare order-insensitive?
>>> from collections import OrderedDict
>>> xy = OrderedDict([('x', None), ('y', None)])
>>> yx = OrderedDict([('y', None), ('x', None)])
>>> xy == yx
False
>>> xy.keys() == yx.keys()
True
The OrderedDict keys view should arguably behave like an OrderedSet, but instead it behaves the same as dict.keys
(i.e. like a usual set
).
Same "issue" in python2:
>>> xy.viewkeys() == yx.viewkeys()
True
They are different types, (odict_keys
is a subclass of dict_keys
)
>>> type(xy.keys())
odict_keys
>>> type({}.keys())
dict_keys
And there is already an order-sensitive keys comparison available that they could have trivially used, but it's apparently only used as a post-check for the odict rich comparison.
Is this a design decision, or a bug? If it's a design decision, where could I find a discussion of the justification?
list(xy) == list(yx)
. – Benjamin Hodgson♦all(x == y for x, y in zip(xy, yx))
if you want slightly lazier evaluation on python3.x – mgilsonlen
too, or useitertools.zip_longest
with a sentinel, or that will returnTrue
if one set of keys is a truncated run of the other keys. You can also push more work to the C layer, running a titch faster for all but the smallest runs by importing at the topfrom operator import eq
and then dolen(xy) == len(yx) and all(map(eq, xy, yx))
at the test site, validating the length first then performing C level key comparisons as efficiently as possible. – ShadowRangerpypy
). MakingKeysView
behave differently for ordered dict than for regular dict might make their implementation more difficult (which is sometimes considered in language decisions as far as I can tell). – mgilson