2011-07-24 48 views
3

我想写一个程序,我的兄弟和我可以输入和编辑我们的足球比赛名册中的信息,比较球队和管理球员等。 这是我尝试过的第一个'大'项目。如何更新字典值让用户选择要更新的密钥,然后在Python中输入新值?

我有一个字典里面的嵌套字典,我能够让用户创建字典等,但是当我尝试让'用户'(通过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 

当然,当我说“应该给......”等我的意思是说:“我希望它给。”

总之我希望用户选择播放器进行编辑,选择STAT编辑,然后选择新的值

+0

“user”? “值”? **“更改”?!** –

+0

您可能想用使用的编程语言标记您的问题。这将通知对该标签/语言感兴趣的人。 – THelper

+2

谢谢THelper。我经常通过我的关于python问题的google查询指向这里,但我并没有想到该网站会涉及其他语言。 – Nathan

回答

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

谢谢spacediver! 我将它改为 vars()[player] [stat_to_edit] = new_value 这很好。 – Nathan

+0

欢迎您,不要犹豫,也可以赞同我的回答;) – spacediver

+0

upvote :)并再次感谢 – Nathan