简体   繁体   中英

Why is the Python dict already sorted?

I have a sorted word frequency file as follows:

the 33333
good 2333
bad 1233
book 500
...

When I created a word_freq = {} dict after reading it from the file, not OrderedDict, surprisingly, the decreasing order by freq is still maintained. Should I use an OrderedDict?

Why is that?

TLDR : If you insert them by size and use Python >= 3.7 (or CPython >= 3.6), it is safe to use a regular dictionary. If you don't - use OrderedDict .


Dictionaries are ordered by the insertion order from Python 3.6. This order was just an implementation detail, the release notes for Python 3.6 said the following:

The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon (this may change in the future, but it is desired to have this new dict implementation in the language for a few releases before changing the language spec to mandate order-preserving semantics for all current and future Python implementations; this also helps preserve backwards-compatibility with older versions of the language where random iteration order is still in effect, eg Python 3.5).

From Python 3.7 onwards, the Python standard requires that dictionaries should be ordered by the insertion order.

DISCLAIMER: The following is only true for Python 3.6 and above


When you read the file and inserted it into the dict, unless you purposely randomized the insertion of the elements into the dict, they would stay in the same order as the file. It did not reorder the dict, but it simply kept the ordered version that the file had.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM