Dictionary iteration, adding keys and values

I would like to iterate over the dictionary dictionary, changing the dictionary every time, and not what is currently happening, which reloads 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 does not change the list, but deletes the previous values. How do I change the dictionary?

(Also, when I run this, he wants me to enter the value BEFORE the key, why is this happening?)

+3
source share
3 answers

In your example, classes (dictionary) are updated every time with a new key pair, values.

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

What you should have done was update a pair of keys, values ​​for the same dict:

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

Try :

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

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

  grades[module].append(grade)

If you are using python 2.5 +:

import collections

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

(: ) 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
0

Source: https://habr.com/ru/post/1784430/


All Articles