pythondictionaryfor-loop

Python: will for loop over dict preserve the order in specific case


I have created a dict with predifined keys, where the keys are strings and the values are arrays. Example:

dict = {
    "p1": [1,2,3],
    "r1": [1,2,3],
    "o1": [1,2,3],
    "y1": [1,2,3],
    "w1": [1,2,3]
}

Then I have logic to manipulate the values of the value arrays(increase/decrease some of the numbers). At the end I'm using for cycle to iterate over the dict like that:

[dict[f][1] for f in dict]

In this case I'm not changing the structure and I'm not adding any new elements in the dict. The question is: Can I be sure that the loop will iterate over the elements in the same order as they were defined initially or I have to specify order to be sure?


Solution

  • Can I be sure that the loop will iterate over the elements in the same order as they were defined initially or I have to specify order to be sure?

    The simplest answer is Yes, according to the documentation below

    In Python 3.7 and later: See Ref docs

    Changed in version 3.7: Dictionary order is guaranteed to be insertion order.

    Code tested using pyenv shell 3.7.17

    >>> my_dict = {
        "p1": [1, 2, 3],
        "r1": [4, 5, 6],
        "o1": [7, 8, 9],
        "y1": [10, 11, 12],
        "w1": [13, 14, 15]
    }
    >>> result = [my_dict[key][1] for key in my_dict] 
    >>> print(result)
    [2, 5, 8, 11, 14]
    >>>