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".
Le ven. 27 juil. 2018 à 07:58, Steven D'Aprano <st...@pearwood.info<mailto:st...@pearwood.info>> a écrit : On Fri, Jul 27, 2018 at 05:30:35AM +0000, Robert Vanden Eynde wrote: > Currently, what's the best way to implement a function > f(OrderedDict([(1,2),(3,4)])) == '{1: 2, 3: 4}', works for all > possible types, and also availaible for pprint with nice indent? I don't understand the question, and I especially don't understand the "all possible types" part. Do you actually mean *all* possible types, like int, float, str, MyClassThatDoesSomethingWeird? But guessing (possibly incorrectly) what you want: py> from collections import OrderedDict py> od = OrderedDict([(1,2),(3,4)]) py> od == {1:2, 3: 4} True If efficiency is no concern, then the simplest way to get something that has a dict repr from an OrderedDict is to use a dict: py> dict(od) {1: 2, 3: 4} This also works as OrderedDict is a subclass of dict, and should avoid the cost of building an entire dict: py> dict.__repr__(od) '{1: 2, 3: 4}' > If I > could set a parameter in ipython or python repl that would print that, > that would already be very useful. See sys.displayhook. -- Steve _______________________________________________ Python-ideas mailing list Python-ideas@python.org<mailto:Python-ideas@python.org> https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/
_______________________________________________ Python-ideas mailing list Python-ideas@python.org https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/