遍历字典,添加键和值

3 投票
3 回答
45190 浏览
提问于 2025-04-16 09:40

我想要遍历一个字典,每次都对字典进行修改,而不是像现在这样用新的值覆盖旧的值。

我现在的代码是:

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

但是可惜的是,这样做并没有修改列表,而是把之前的值给删掉了。我该怎么做才能修改字典呢?

(另外,当我运行这个的时候,它让我先输入值再输入键,这是什么原因呢?)

3 个回答

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
3
grades = {}
while True:
  module = raw_input(...)
  grade = raw_input(...)

  if not grades[module]:
    grades[module] = []

  grades[module].append(grade)
import collections

grades = collections.defaultdict(list)
while True:
  grades[raw_input('enter module')].append(raw_input('enter grade'))

如果你在使用 Python 2.5 及以上版本:

20

在你的例子中,成绩(字典)每次都会用一个新的键值对来刷新。

>>> 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', '': ''}
>>> 

撰写回答