如何检查字典中是否有值

时间:2019-09-19 04:10:48

标签: python python-3.x tkinter

我正在编写一个国际象棋程序,而此功能可以移动棋子。但是,它当前不触发条件: if self.square in player.position.values()==True:,当我尝试检查变量self.square是否在字典位置时,它会直接进入else。有更好的方法吗?对于该部分功能,我的完整代码为:

if self.square==(-10,-10):
    self.square=squareposition
    print("it gets to here")
    if self.square in player.position.values()==True:
        print("it currently doesn't get to here. It goes into the else")
        for key in player.position:
            pieceposition=player.position.get(key)
            if self.square==pieceposition:
                self.piece=key
                break
            else:
                pass
    else:
        self.gamelabel.config(text="Error no " +str(turn)+" piece on this square please try again")
        self.square==(-10,-10)

1 个答案:

答案 0 :(得分:3)

假设self.square是您要查找的值,而player.position是字典,则只需:

if self.square in player.position.values():