Will a Python dict literal be evaluated in the order it is written?

后端 未结 3 1602
终归单人心
终归单人心 2020-12-10 02:44

Let\'s say that I\'ve got a situation like this in Python:

_avg = {\'total\':0.0, \'count\':0}    # HACK: side-effects stored here

def procedure(n):
  _avg[         


        
3条回答
  •  被撕碎了的回忆
    2020-12-10 03:24

    According to the Python docs regarding evaluation order, this should have well-defined behavior:

    In the following lines, expressions will be evaluated in the arithmetic order of their suffixes:

    …
    {expr1: expr2, expr3: expr4}
    …
    

    So, regardless of what order the items in a dict end up being iterated, the values (and keys!) of a literal dictionary expression will always be evaluated in the same order as they appear in my Python source code.

提交回复
热议问题