Looping through dictionary and getting keys

This question already has an answer here:

  • Iterating over dictionaries using 'for' loops 12 answers

  • 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/30368.html

    上一篇: 在类中使用'for'循环迭代字典

    下一篇: 循环使用字典并获取密钥