Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> OrderedDict - dictionary that maintains order of key-value pairs (e.g. when HTTP header value matters for dealing with certain security mechanisms).

Word to the wise... as of Python 3.7, the regular dictionary data structure guarantees order. Declaring an OrderedDict can still be worthwhile for readability (to let code reviewers/maintainers know that order is important) but I don't know of any other reason to use it anymore.



Comparison of OrderedDict is order-sensitive. They also have some extra methods.


Yep, those extra methods are extremely useful. Basically turns them into stack/queues in addition to being dictionaries which can be very helpful.


Being as specific as possible with your types is how you make things more readable in Python. OrderedDict where the order matters, set where there are no duplicate items possible, The newish enums are great for things that have a limited set of values (dev, test, qa, prod) vs using a string. You can say a lot with type choice.

Another reason is I think that 3.7 behavior is just a C Python implementation detail, other interpreters may not honor it.


> Being as specific as possible with your types is how you make things more readable in Python.

If Dict already guarantees to keep Order, nothing ist won by using both Dict and OrderedDict. Just use Dict.


The mere fact we're having this discussion means people don't know the guarantees and be being more explicit there is less room for confusion.



> Word to the wise... as of Python 3.7, the regular dictionary data structure guarantees order.

Which means you still should use it if you might run on 3.6 or earlier.


Even for 3.6 it's still true, just not guaranteed in writing: https://stackoverflow.com/a/39980744/5044950

And Python <=3.7 is already end-of-life anyways: https://devguide.python.org/versions/


This hit me bad once bad. I tested the regular dict and it _looked_ like it was ordered. Turned out, 1 out of about 100000 times it was not. And I had a lot of trouble identifying the reason 3 weeks later, when the bug was buried deep in complex code, and it appeared mostly what looked like random.


Does dict now guarantee that it maintains order? IIRC, it was originally a mere side effect of the algorithm chosen (which was chosen for performance), but it could change in future releases or alternative implementations.


>Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.

https://docs.python.org/3/library/stdtypes.html#dict:~:text=....


afaik the documentation states that it could change in the future


Nope, "Dict keeps insertion order" is the ruling.

https://mail.python.org/pipermail/python-dev/2017-December/1...




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: