迭代时将项添加到dict中

2024-04-27 00:46:01 发布

您现在位置:Python中文网/ 问答频道 /正文

在迭代字典时向字典添加项有多安全?乍一看是挺管用的,但我想知道是否有不安全的情况。 键是字符串01…等等


Tags: 字符串字典情况时向
2条回答

使用items()或keys()方法可以安全地修改dict。items()返回dict键的副本,value pairs和keys()返回dict键的副本。你知道吗

>>> foo = {'spam': 'egg'}
>>> for k, v in foo.items():
...  foo['egg'] = 'spam'

迭代时不能更改词典的大小:

>>> foo = {'spam': 'egg'}
>>> for i in foo:
...  foo['egg'] = 'spam'
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration

你必须先复印一份:

>>> foo = {'spam': 'egg'}
>>> for i in dict(foo):
...  foo['egg'] = 'spam'
... 
>>> foo
{'spam': 'egg', 'egg': 'spam'}

相关问题 更多 >