Why is Python's OrderedDict ordered?

(piglei.com)

11 points | by misonic 5 days ago

2 comments

  • DemocracyFTW2 5 days ago
    Wrong title, article has "How Does Python’s OrderedDict Maintain Order?"
  • addaon 5 days ago
    Title of the article is "How…", not "Why…", and "why" is not discussed. (My understanding is that the "why" is "because the implementation acted that way without an official guarantee, and folks depended on the implementation detail, so it became guaranteed.)
    • recursivecaveat 8 hours ago
      I was under that impression as well, but it was added as an implementation in 3.6 (https://bugs.python.org/issue27350), so I don't know that too many people would have become dependent on it before it was official in 3.7: https://docs.python.org/3/whatsnew/3.7.html

      I think the "how/why" thing is just the automatic title de-clickbait-ifer going a little haywire?

    • DemocracyFTW2 5 days ago
      I don't think this is the "why". What you're depicting is what happened in JavaScript. Dictionary keys in Python always had that (to me) annoying property that they preserved insertion order until they don't. I'd frankly much prefer if they'd always be iterated in random order each time they're traversed.
      • not_kurt_godel 8 hours ago
        I'd love to see the results of mandating a random order dict impl at an actual company/org (but hate to be forced to participate). Hopefully you hired developers who really like to write sorting algos.
        • nielsbot 8 hours ago
          Swift (heavily used by Apple) has randomly ordered dictionaries for security:

          > In particular, random seeding enables better protection against (accidental or deliberate) hash-flooding attacks

          https://forums.swift.org/t/psa-the-stdlib-now-uses-randomly-...

        • yxhuvud 8 hours ago
          Well, that is how hash tables in go works, so you'd not have to look that far.
          • tasty_freeze 8 hours ago
            Perl since 5.8.something has had the option of perturbing the hash function, so it is different from run to run. You can also set the set to a given value in order to lock in the sequence.

            In any case, it is not ordered. If you want that, you have to explicitly sort the keys of the hash.

          • not_kurt_godel 8 hours ago
            Great. Maybe GP will go a step farther and also mandate arrays that return elements in random order too. Relying on insertion order for any reason is for weaklings.
    • snthpy 4 hours ago
      Thanks, How makes much more sense. The post title is dumb.

      Why is Hackernews news for hackers?