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

Robert Vanden Eynde robertve92 at gmail.com
Fri Jul 27 07:24:22 EDT 2018


Sorry Steven I didn't see your clever dict.__repr__ solution that Chris
pointed out too. That's what I was looking for ^^

And now for pprint, apparently that doesn't seem difficult to implement.

About the part where "the representation looses the type information",
pformat(od) could be "OrderedDict{1:2, 3,4}" or "OrderedDict({1:2, 3:4})"
but I don't ask for repr or pprint to change, just curious about how to
implement that.

</my_parenthesis>

Le ven. 27 juil. 2018 à 11:53, Chris Angelico <rosuav at gmail.com> a écrit :

> 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
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180727/8432389b/attachment.html>


More information about the Python-ideas mailing list