如何在Python中更新字典的值,让用户选择要更新的键和新值?
我正在尝试写一个程序,让我和我哥哥可以输入和编辑我们足球比赛的阵容信息,以便比较球队和管理球员等等。这是我尝试的第一个“大”项目。
我在一个字典里面有一个嵌套的字典,我能让用户创建这些字典。但是当我想让用户(通过输入)回去编辑这些字典时,我就卡住了。下面我尝试写了一个简化版的代码,觉得和我的错误有关。如果需要我提供完整的代码,请告诉我。
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
问题出在这一行之后:
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}
>>>