Как обновить значение словаря, когда пользователь выбирает ключ для обновления, а затем новое значение в Python? - PullRequest
3 голосов
/ 24 июля 2011

Я пытаюсь написать программу, в которой мы с братом можем вводить и редактировать информацию из наших списков футбольных игр, сравнивать команды и управлять игроками и т. Д. Это мой первый «большой» проект, который я пробовал.

У меня есть вложенный словарь внутри словаря, я могу заставить пользователя создавать словари и т. Д. Но когда я пытаюсь заставить 'user' (через raw_input) вернуться, чтобы редактировать их, я застреваю. Ниже я попытался изложить упрощенную версию кода, которая, по моему мнению, имеет отношение к моей ошибке. Если мне нужно записать полную версию, дайте мне знать.

player1 = {'stat1' : A, 'stat2' : 2, 'stat3' : 3} #existing players are the dictionaries 
player2 = {'stat1' : A, 'stat2' : 2, 'stat3' : 3} # containing the name of stat and its value
position1 = {'player1' : player1} # in each position the string (name of player) is the key and
position2 = {'player2' : player2} # the similarly named dict containing the statisics is the value
position = raw_input('which position? ') # user chooses which position to edit
if position == 'position1':
  print position1 # shows user what players are available to choose from in that position
  player = raw_input('which player? ') #user chooses player from available at that position
  if player == player1:
    print player # shows user the current stats for the player they chose
    edit_query = raw_input('Do you need to edit one or more of these stats? ')
    editloop = 0
    while editloop < 1: # while loop to allow multiple stats editing
      if edit_query == 'yes': 
        stat_to_edit = raw_input('Which stat? (If you are done type "done") ')
          if stat_to_edit == 'done': #end while loop for stat editing
            editloop = editloop +1
          else:
            new_value = raw_input('new_value: ') #user inserts new value

# up to here everything is working. 
# in the following line, player should give the name of the
# dictionary to change (either player1 or player2) 
# stat_to_edit should give the key where the matching value is to be changed
# and new_value should update the stastic
# however I get TypeError 'str' object does not support item assignment

            player[stat_to_edit] = new_value #update statistic
      else:  # end loop if no stat editing is wanted
        fooedit = fooedit + 1

конечно, когда я говорю "должен дать ..." и т. Д., Я имею в виду сказать "я хочу, чтобы он дал ..."

В итоге я хочу, чтобы пользователь выбрал игрока для редактирования, выберите статистику для редактирования, затем выберите новое значение

1 Ответ

2 голосов
/ 24 июля 2011

Похоже, проблема в том, что после этой строки

player = raw_input('which player? ')

player будет строкой, содержащей то, что набрал пользователь, а не словарь, как player1. Это объясняет, почему Python не может назначить свою часть. Вместо этого вы можете написать так:

player = raw_input('which player? ')
if player == 'player1': # these are strings!
  current_player = player1 # this is dictionary!
  ....
  current_player[...] = ... # change the dictionary

Также обратите внимание, что присвоение Python имени обычно не копирует объект, а только добавляет другое имя для того же существующего объекта. Рассмотрим этот пример (из консоли Python):

>>> a = {'1': 1}
>>> a
{'1': 1}
>>> b = a
>>> b
{'1': 1}
>>> b['1'] = 2
>>> b
{'1': 2}
>>> a
{'1': 2}
>>>
...