Python 3.6字典遍历有序原因咨询:原认知为无序数据结构
Great question—this is a common point of confusion for folks moving between Python versions, so let's break it down clearly:
The 3.6 Implementation Shift
In Python 3.6, CPython (the standard Python interpreter) got a major overhaul to its dictionary internals. The team switched to a more memory-efficient "compact hash table" design, and as a side effect of this optimization, dictionaries started retaining the insertion order of key-value pairs. But here’s the critical detail: this was not an official language rule at the time—it was just an unintended (but welcome) consequence of the new implementation. Other Python interpreters (like PyPy) might not have had this behavior in 3.6.Official Guarantee in 3.7+
Developers loved the ordered behavior so much that Python 3.7 formalized it: preserving insertion order became part of the Python language specification, not just a CPython quirk. Now, no matter which compliant interpreter you use, standard dictionaries will always keep your key-value pairs in the order you added them.Test It Yourself
Here’s a quick snippet to verify this behavior:my_dict = {} my_dict['first'] = 1 my_dict['second'] = 2 my_dict['third'] = 3 for key in my_dict: print(key)Run this in Python 3.6, and you’ll see
first,second,thirdin order. Try it in 3.5 or earlier, and the output order will be random.A Quick Note on
OrderedDict
Before 3.6, if you needed guaranteed ordered dictionaries, you’d usecollections.OrderedDict. Even today,OrderedDicthas some unique features (like themove_to_end()method) that regular dicts don’t offer, but for basic insertion order preservation, regular dicts are sufficient in 3.7+.
内容的提问来源于stack exchange,提问作者user9282534

