[Python-ideas] Change repr of collections.OrderedDict to be more dict-like
Chris Angelico
rosuav at gmail.com
Fri Jul 27 09:29:52 EDT 2018
On Fri, Jul 27, 2018 at 9:24 PM, Serhiy Storchaka <storchaka at gmail.com> wrote:
> 27.07.18 12:53, Chris Angelico пише:
>>>>>
>>>>> from collections import OrderedDict
>>>>> od = OrderedDict([('a', 1), ('b', 2)])
>>>>> dict.__repr__(od)
>>
>> "{'a': 1, 'b': 2}"
>
>
> dict.__repr__() can output items in wrong order.
>
>>>> from collections import OrderedDict
>>>> od = OrderedDict([('a', 1), ('b', 2)])
>>>> od.move_to_end('a')
>>>> print(repr(od))
> OrderedDict([('b', 2), ('a', 1)])
>>>> print(dict.__repr__(od))
> {'a': 1, 'b': 2}
>
Ah, fair point. Interestingly, the same problem hits repr(dict(od)),
which I would have thought a reliable solution here. The simplest way
that I've found is:
>>> dict(od.items())
{'b': 2, 'a': 1}
That seems very odd. Iterating over the OD produces its keys in the
correct order (b, a), but constructing a dict from it ignores
iteration order and just goes "oh hey, this is a dict, we can snag
that". Is that correct?
ChrisA
More information about the Python-ideas
mailing list