Python 迭代字典,添加键和值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4642258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 16:42:13  来源:igfitidea点击:

Iterating on a dictionary, adding keys and values

pythondictionaryiterationamend

提问by Hypergiant

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?)

(此外,当我运行它时,它希望我在键之前输入值,为什么会发生这种情况?)

采纳答案by pyfunc

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

回答by Ivo Wetzel

You're reassigning (read: replacing) gradeson 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

回答by sjr

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'))