"will a python dict literal be evaluated in the order it is written?" Code Answer


dictionary evaluation order should be the same as written, but there is a outstanding bug where values are evaluated before the keys. (the bug was finally fixed in python 3.5).

quoting from the reference documentation:

python evaluates expressions from left to right.

and from the bug report:

running the following code shows "2 1 4 3", but in reference manual http://docs.python.org/reference/expressions.html#expression-lists the evaluation order described as {expr1: expr2, expr3: expr4}

def f(i):
    print i
    return i

{f(1):f(2), f(3):f(4)}

and guido stated:

i am sticking with my opinion from before: the code should be fixed. it doesn't look like assignment to me.

this bug is fixed in python 3.5, so on python 3.4 and earlier the values are still evaluated before the keys:

>>> import sys
>>> sys.version_info
sys.version_info(major=3, minor=4, micro=2, releaselevel='final', serial=0)
>>> def f(i):
...     print(i)
...     return i
>>> {f(1):f(2), f(3):f(4)}
{1: 2, 3: 4}

since your code doesn't require the keys to be evaluated first, your code is guaranteed to work correctly; key-value pairs are still evaluated in order even if the keys are evaluated after each corresponding value.

By LiverpoolsNumber9 on April 6 2022

Answers related to “will a python dict literal be evaluated in the order it is written?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.