【问题标题】:Looping through dictionary and getting keys [duplicate]遍历字典并获取键[重复]
【发布时间】:2015-10-25 00:02:06
【问题描述】:

我正在尝试获取字典中的名称及其对应的键值。 对不起,如果这已经被问到了。这段代码不起作用,因为我很擅长编程并且刚刚开始。请告诉我它有什么问题。

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

【问题讨论】:

  • 好吧,你永远不会关闭你的字典,并且要遍历字典使用 for k, v in theBoard.items()
  • 下次用谷歌搜索你的问题,顶部会出现关于SO的相关答案。此外,在您撰写问题时,标题为可能已经有您的答案的问题的列表会显示可能相关的问题。 使用该列表并在新标签中打开建议的问题。这个网站已经存在了 6 年多了,如果你怀疑某个问题已经被问过,它可能已经问过了。这样的重复只会浪费时间和精力。

标签: python dictionary


【解决方案1】:
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

【讨论】:

    【解决方案2】:
    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
    

    我认为你的标签也关闭了......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-14
      • 1970-01-01
      • 1970-01-01
      • 2017-08-30
      • 2015-09-27
      • 1970-01-01
      • 2011-06-24
      • 1970-01-01
      相关资源
      最近更新 更多