简体   繁体   English

迭代字典,添加键和值

[英]Iterating on a dictionary, adding keys and values

I would like to iterate on a dictionary, amending the dictionary each time rather than what is currently happening which is resetting the old value with the new one.我想迭代字典,每次修改字典而不是当前正在发生的事情,即用新值重置旧值。

My current code is:我目前的代码是:

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

but alas, this doesn't amend the list, but rather removes the previous values.但唉,这不会修改列表,而是删除以前的值。 How would I go about amending the dictionary?我将如何修改字典?

(Also, when I run this, it wants me to input the value BEFORE the key, why does this happen?) (此外,当我运行它时,它希望我在键之前输入值,为什么会发生这种情况?)

In your example, grades (dictionary) is getting refreshed each time with a new key,value pair.在您的示例中,成绩(字典)每次都会使用新的键值对进行刷新。

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

What you should have been doing is update the key,value pair for the same dict:你应该做的是更新同一个字典的键值对:

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

Try this :试试这个

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

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

  grades[module].append(grade)

If you're using python 2.5+:如果您使用的是 python 2.5+:

import collections

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

You're reassigning (read: replacing) grades on each iteration, of the loop.您在循环的每次迭代中重新分配(读取:替换) grades

You need to actually set new keys of the dictionary:您需要实际设置字典的新键:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM