循环使用字典并获取密钥

这个问题在这里已经有了答案:

  • 使用'for'循环遍历字典12个答案

  • 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
    

    我认为你的绊脚石也是...

    链接地址: http://www.djcxy.com/p/30367.html

    上一篇: Looping through dictionary and getting keys

    下一篇: Iterate through each key and it's value, of a function