Is the order of a Python dictionary guaranteed over iterations?

后端 未结 6 1596
轮回少年
轮回少年 2020-12-15 15:52

I\'m currently implementing a complex microbial food-web in Python using SciPy.integrate.ode. I need the ability to easily add species and reactions to the system, so I have

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-15 16:05

    Yes, the same order is guaranteed if it is not modified.

    See the docs here.

    Edit:

    Regarding if changing the value (but not adding/removing a key) will affect the order, this is what the comments in the C-source says:

    /* CAUTION: PyDict_SetItem() must guarantee that it won't resize the
     * dictionary if it's merely replacing the value for an existing key.
     * This means that it's safe to loop over a dictionary with PyDict_Next()
     * and occasionally replace a value -- but you can't insert new keys or
     * remove them.
     */
    

    It seems that its not an implementation detail, but a requirement of the language.

提交回复
热议问题