Looping through dictionary and getting keys
本问题已经有最佳答案,请猛点这里访问。
我正在试图从字典中获取名称及其对应的键值。对不起,如果已经问过了。这段代码不起作用,因为我在编程方面很差劲,刚开始。请告诉我它出了什么问题。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ', 'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ', 'low-L': ' ', 'low-M': ' ', 'low-R': ' ' 'Check for closed moves' def openMoves: for i in theBoard: if theBoard[i] == ' ': print"the move %s is open" % theBoard[i] else: print"the move %s is taken" % theBoard[i] print openMoves() |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ', 'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ', 'low-L': ' ', 'low-M': ' ', 'low-R': ' ' } # <--- Close your dictionary # <--- remove random string 'Check for c...' def openMoves(): # <--- add parenthesis to function for k, v in theBoard.items(): # <--- loop over the key, value pairs if v == ' ': print"the move %s is open" % k else: print"the move %s is taken" % k openMoves() # <-- remove the print statement |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ', 'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ', 'low-L': ' ', 'low-M': ' ', 'low-R': ' '} def openMoves(): for k,v in theBoard.items(): if v == ' ': print"the move %s is open" %k else: print"the move %s is taken" %k |
我认为那是你的tabbing太……