0

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?

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
Grak
  • 99
  • 1
  • 12

1 Answers1

2

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 (See: Dictionaries are ordered in Python 3.6+) 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.

Community
  • 1
  • 1
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
  • So basically, the only clunky way to do it is to make a list of the keys first and... Magic? Ugh, this is pretty annoying. – Grak Nov 25 '16 at 12:28
  • @Grak but that's how dictionaries are implemented. If you require order why not hold them, as John suggested, in an ordered sequence like a list? – Dimitris Fasarakis Hilliard Nov 25 '16 at 12:31