[Python-ideas] Change repr of collections.OrderedDict to be more dict-like

Chris Angelico rosuav at gmail.com
Fri Jul 27 05:53:50 EDT 2018


On Fri, Jul 27, 2018 at 7:45 PM, Thomas Jollans <tjol at tjol.eu> wrote:
> On 27/07/18 08:06, Robert Vanden Eynde wrote:
>
> Thanks for your response, I want to print/repr an OrderedDict() without
> relying on the fact that "dict are ordered" ie. I want a solution < python
> 3.7.
> Currently, if I do repr( OrderedDict([(1,2),(3,4)]) ), I get the string
> "OrderedDict([(1,2),(3,4)])", I'd like a function that would return the
> string "{1: 2, 3: 4}" in the correct order.
> If I do repr(dict( OrderedDict([(1,2),(3,4)]) )) I get "{1: 2, 3: 4}"
> because dict are ordered since python 3.7.
> And for pprint, currently pformat( OrderedDict([(1,2),(3,4)]) ) gives the
> string 'OrderedDict([(1, 2), (3, 4)])' (and adds \n for bigger dict).
> I could do pprint(dict( OrderedDict([(1,2),(3,4)]) )) but again that relies
> on python 3.7 behavior.
> I'm wondering if there exists an easy way to code this "order preserving
> repr and pprint/pformat".
>
>
> It's a fairly non-standard thing to do as you're not representing the
> ordered dict itself, but it's easy enough...
>
>>>> od = OrderedDict([('a', 1), ('b', 2)])
>>>> '{%s}' % ', '.join('{!r}: {!r}'.format(k, v) for (k, v) in  od.items())
> "{'a': 1, 'b': 2}"
>>>>
>
> It's a bit more work if you want pretty-printing.
>
> And there's always json.

>>> from collections import OrderedDict
>>> od = OrderedDict([('a', 1), ('b', 2)])
>>> dict.__repr__(od)
"{'a': 1, 'b': 2}"

:)

ChrisA


More information about the Python-ideas mailing list