python dictionary is thread safe?

后端 未结 4 1722
小鲜肉
小鲜肉 2020-12-01 10:56

Some stated that python dictionary is thread safe. Does it mean I can or cannot modify the items in a dictionary while iterating over it?

4条回答
  •  -上瘾入骨i
    2020-12-01 11:09

    No. Recent version of python will raise an exception if you try to iterate over a dictionary that has changed size between iterations.

    >>> d={'one':1, 'two':2}
    >>> for x in d:
    ...    d['three']=3
    ...    print x
    ...
    two
    Traceback (most recent call last):
      File "", line 1, in 
    RuntimeError: dictionary changed size during iteration
    

    Notice that you don't need to use threads to see this

提交回复
热议问题