Pergunta

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

Foi útil?

Solução

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

Outras dicas

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+:

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.

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
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top