Итализация в словаре, добавление клавиш и значений

StackOverflow https://stackoverflow.com/questions/4642258

Вопрос

Я хотел бы итерации в словаре, внесении изменения в словарь каждый раз, а не то, что в настоящее время происходит, что сбрасывает старое значение с новым.

Мой текущий код:

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

Но увы, это не вносит изменения в список, а скорее удаляет предыдущие значения. Как бы я пошел по внесению поправок в словарь?

(Кроме того, когда я запускаю это, он хочет, чтобы я ввел значение до ключа, почему это происходит?)

Это было полезно?

Решение

В вашем примере оценки (словарь) одновременно обновляются с новым ключом, Value Pair.

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

То, что вы должны были делать, это обновить ключ, вариант по стоимости для того же Dict:

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

Другие советы

grades = {}
while True:
  module = raw_input(...)
  grade = raw_input(...)

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

  grades[module].append(grade)

Если вы используете Python 2.5+:

import collections

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

Вы переназначиваете (читай: замена) 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
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top