gpt4 book ai didi

python - 迭代字典,添加键和值

转载 作者:太空宇宙 更新时间:2023-11-03 12:14:47 25 4
gpt4 key购买 nike

我想迭代字典,每次都修改字典,而不是当前正在发生的用新值重置旧值的情况。

我当前的代码是:

while True:
grades = { raw_input('Please enter the module ID: '):raw_input('Please enter the grade for the module: ') }

但是,唉,这并没有修改列表,而是删除了以前的值。我将如何修改字典?

(另外,当我运行它时,它要我在键之前输入值,为什么会这样?)

最佳答案

在您的示例中,成绩(字典)每次都会使用新的键值对进行刷新。

>>> grades = { 'k':'x'}
>>> grades
{'k': 'x'}
>>> grades = { 'newinput':'newval'}
>>> grades
{'newinput': 'newval'}
>>>

你应该做的是更新同一个字典的键值对:

>>> grades = {}
>>> grades['k'] = 'x'
>>> grades['newinput'] = 'newval'
>>> grades
{'k': 'x', 'newinput': 'newval'}
>>>

试试这个:

>>> grades = {}
>>> while True:
... k = raw_input('Please enter the module ID: ')
... val = raw_input('Please enter the grade for the module: ')
... grades[k] = val
...
Please enter the module ID: x
Please enter the grade for the module: 222
Please enter the module ID: y
Please enter the grade for the module: 234
Please enter the module ID: z
Please enter the grade for the module: 456
Please enter the module ID:
Please enter the grade for the module:
Please enter the module ID: Traceback (most recent call last):
File "<stdin>", line 2, in <module>
KeyboardInterrupt
>>>
>>> grades
{'y': '234', 'x': '222', 'z': '456', '': ''}
>>>

关于python - 迭代字典,添加键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4642258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com