我想迭代字典,每次修改字典而不是当前正在发生的字典,而是用新的字符重置旧值。
我目前的代码是:
while True:
grades = { raw_input('Please enter the module ID: '):raw_input('Please enter the grade for the module: ') }
但是,这不会修改列表,而是删除以前的值。我该如何修改字典?
(另外,当我运行它时,它希望我在键之前输入值,为什么会发生这种情况?)
答案 0 :(得分:17)
在您的示例中,每次使用新的键值组都会刷新成绩(字典)。
>>> 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', '': ''}
>>>
答案 1 :(得分:2)
grades = {}
while True:
module = raw_input(...)
grade = raw_input(...)
if not grades[module]:
grades[module] = []
grades[module].append(grade)
如果您使用的是python 2.5 +:
import collections
grades = collections.defaultdict(list)
while True:
grades[raw_input('enter module')].append(raw_input('enter grade'))
答案 2 :(得分:0)
你在循环的每次迭代中重新分配(读取:替换)grades
。
您需要实际设置字典的新键:
grades = {}
while True: // some end condition would be great
id = raw_input('Please enter the module ID: ')
grade = raw_input('Please enter the grade for the module: ')
// set the key id to the value of grade
grades[id] = grade