2

The insertion-order of keyword arguments is now guaranteed to be preserved in the 3.6 version of Python. This has been made possible by a change to the underlying representation of the dict object.

However, it has been stated - somewhat strenuously - that the order preservation of the dict object should not be relied upon in general as of yet. The docs explain the situation this way:

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, e.g. Python 3.5).

PEP 468 does not mention anything about copying the keyword arguments. But there are times when one may wish to iterate over a copy of the kwargs arguments (e.g. while mutating kwargs in a for loop):

def i_will_never_fail(**kwargs):
    for thing1,thing2 in zip(kwargs.copy(), kwargs):
        assert thing1==thing2

My question is: should the order of the object resulting from kwargs.copy() be considered guaranteed as well? Or should this also be considered an implementation detail? Is the OrderedDict only mostly dead?

Rick
  • 43,029
  • 15
  • 76
  • 119

1 Answers1

1

The answer would be implementation dependent.

Assuming the highly popular CPython, the answer would be yes. As you can see from the PyDict_Copy function (line 2615) in the dictobject.c code, along with increasing references for the values, the function starts the copying with the piece

split_copy->ma_keys = mp->ma_keys;

this, after mp had been assigned the dicitionary object (or more exactly, an explicit casting of the original dict into a PyDictObject).

Since the keys preserve their order, and considering the current form of storage (as seen in Jim's explanation here), the resulting dictionary should be ordered the same way.

Again, that is currently considered an implementation detail and you should not make any of your code depend on it.

Uriel
  • 15,579
  • 6
  • 25
  • 46