2016-05-13 60 views
0

我想插頁新的密鑰,值對進入以前沒有定義更新詞典在Python

這裏的變量是我想要做的:

def drawboard(nextmove): 
    result = nextmove 

    pos = 1 
    print result 

    for i in range(7): 
     for j in range(7): 
      if (j == 0 or i % 2 == 0 or j % 2 == 0): 
       print '*', 
      if (i % 2 != 0 and j % 2 != 0): 
       print pos, 
       pos += 1 
      if (j == 6): 
       print '\n' 
    move = raw_input("Input you move(i.e. x,3[position, your symbol]: ") 
    if move == 'q': 
     exit() 

    calcres(move) 


def calcres(move): 
    nextmove = dict([move.split(',')]) 
    drawboard(nextmove) 


drawboard({0: 0}) 

drawboard功能我想連接nextmove結果,並最終將結果保存在結果中。我嘗試初始化result = {},但按預期從結果中刪除所有項目並重新初始化,結果只有一個項目在該字典內。

回答

1

使用setdefault每當關鍵是不存在初始化result字典值空列表

def drawboard(nextmove): 

    result.setdefault(nextmove[0],[]).append(nextmove[1]) 
    pos = 1 
    #print result 

    for i in range(7): 
     for j in range(7): 
      if (j == 0 or i % 2 == 0 or j % 2 == 0): 
       print '*', 
      if (i % 2 != 0 and j % 2 != 0): 
       print pos, 
       pos += 1 
      if (j == 6): 
       print '\n' 
    move = raw_input("Input you move(i.e. x,3[position, your symbol]: ") 
    if move == 'q': 
     exit() 

    calcres(move) 


def calcres(move): 
    nextmove = move.split(',') 
    drawboard(nextmove) 

result = {} 
drawboard([0,0])