Yes, any method of constructing a dict preserves insertion order, in Python 3.7+.
For dict literals, see Martijn's answer on How to keep keys/values in same order as declared?. Also, from the documentation:
If a comma-separated sequence of key/datum pairs is given, they are evaluated from left to right to define the entries of the dictionary: [...]
For comprehensions, from the same source.
When the comprehension is run, the resulting key and value elements are inserted in the new dictionary in the order they are produced.
Lastly, the dict
initializer works by iterating over its argument and keyword arguments, and inserting each in order, similar to this:
def __init__(self, mapping_or_iterable, **kwargs):
if hasattr(mapping_or_iterable, "items"): # It's a mapping
for k, v in mapping_or_iterable.items():
self[k] = v
else: # It's an iterable of key-value pairs
for k, v in mapping_or_iterable:
self[k] = v
for k, v in kwargs.items():
self[k] = v
(This is based on the source code, but glossing over a lot of unimportant details, e.g. that dict_init
is just a wrapper on dict_update_common
. Also note that I don't know C, but I got the gist of it.)
This, combined with the fact that keyword arguments pass a dictionary in the same order since Python 3.6, makes dict(x=…, y=…)
preserve the order of the variables.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…