簡體   English   中英

如何在Python中更新字典值,讓用戶選擇要更新的密鑰,然后選擇新值?

[英]How do I update a dictionary value having the user choose the key to update and then the new value, in Python?

我正在嘗試編寫一個程序,我和我的兄弟可以從我們的足球比賽名單中輸入和編輯信息來比較球隊和管理球員等。這是我嘗試的第一個“大”項目。

我在字典中有一個嵌套字典,我能夠讓用戶創建字典等。但是當我嘗試使用'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

當然,當我說“應該給......”等我的意思是說“我希望它給......”

總之,我希望用戶選擇要編輯的播放器,選擇要編輯的統計數據,然后選擇新值

問題似乎在這一行之后

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}
>>>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM