在字典中循环查找并获取密钥

2024-09-26 22:13:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着在字典里找到名字和它们对应的键值。 抱歉,如果已经有人问过了。这个代码不工作,因为我在编程和刚开始。请告诉我怎么了。在

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()

Tags: the代码formove字典istop编程
2条回答
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
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

我想你的标签也掉了。。。在

相关问题 更多 >

    热门问题