Grak Grak - 4 months ago 28
Python Question

How to order a dictionary without using _collections or other library?

So I'm supposed to make a dictionary get ordered, and the way I'm doing it now is not valid;

dictionary = _collections.OrderedDict(sorted(dictionary.items()))

because it uses the library "_collections", is there any compact way to do this without an imported library?


No there isn't. If you want ordering you'll have to resort to using OrderedDict; that is the only means to retain order in a dict-like object for Python <= 3.5.

From Python 3.6, dictionaries remember the order of insertion by default so, you'll be able to feed a sorted sequence to it and get the ordering without use of any other modules (e.g OrderedDict). Despite this, it is best to wrap it in an OrderedDict; the ordering behavior of dicts in 3.6 is considered an implementation detail that you should not depend on.