我想在 for 循环中更新字典项。这是我所拥有的:
>>> d = {}
>>> for i in range(0,5):
... d.update({"result": i})
>>> d
{'result': 4}
但我想要 d 有以下项目:
{'result': 0,'result': 1,'result': 2,'result': 3,'result': 4}
请您参考如下方法:
字典的全部思想是它们有唯一的键。 您可以做的是将 'result' 作为键,将 list 作为值,然后继续追加到列表中。
>>> d = {}
>>> for i in range(0,5):
... d.setdefault('result', [])
... d['result'].append(i)
>>> d
{'result': [0, 1, 2, 3, 4]}
