12

Whyyy are dictionaries unordered in python. Fuuuck.

(Yes I know of OrderedDict, no you don't have to remind me - it is not a native data type, it is a module: argument over)

Comments
  • 4
    In version 3.6 dict's keys are in sorted order.
  • 3
    You can always sort the keys in some other data structure. Why is it a problem?

    In addition dictionaries are supposed to work 'like' hash arrays and since hashes are not ordered neither are keys in dict
  • 3
    @kpenc Python has said that this is not a feature, just a side effect of something they did to make dicts more compact. They said, and I quote, "The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon"
  • 0
    Phew, now I know :D

    Mind if I ask if lists are ordered?
  • 0
    @darksideplease If you need a sorted list of keys to iterate over, just use

    sorted(my_dict.keys())
  • 1
    @honeyBadgerJeff Lists and tuples retain the order that you create them in.
  • 1
    So there are people ranting about why there was only ordered map before C++11. Just find that interesting.
  • 0
    @mojaveazure yeah, thats what i use. But in another part of my code i wanted to rely upon the index of the key, ya know - flat data structures are nice.
    Btw: you can even ditch ".keys()" because if you use it as an iterable it automatically returns only the keys.
Add Comment