参见英文答案 >
Will a Python dict literal be evaluated in the order it is written? 3个
当我跑这个
当我跑这个
import itertools bar = itertools.count(1).next print {'a': bar(),'b': bar(),'c': bar()}
在cpython上,我得到{‘a’:0,’b’:1,’c’:2}.这在实施中是否一致和/或在任何地方都有记录? a,b和c是否会被无序分配值?
解决方法
从
Python Docs(强调我的):
If a comma-separated sequence of key/datum pairs is given,they are evaluated from left to right to define the entries of the dictionary: each key object is used as a key into the dictionary to store the corresponding datum….
因此,将始终按顺序评估对.但不要混淆元素的顺序.