-1

I have dictionary like below

x_wins = {'row1_X': 'X' == x_o[0] and 'X' == x_o[1] and 'X' == x_o[2],
'row2_X' : 'X' == x_o[3] and 'X' == x_o[4] and 'X' == x_o[5],
'row3_X' : 'X' == x_o[6] and 'X' == x_o[7] and 'X' == x_o[8],
'col1_X' : 'X' == x_o[0] and 'X' == x_o[3] and 'X' == x_o[6],
'col2_X' : 'X' == x_o[1] and 'X' == x_o[4] and 'X' == x_o[7],
'col3_X' : 'X' == x_o[2] and 'X' == x_o[5] and 'X' == x_o[8],
'slant1_X' : 'X' == x_o[0] and 'X' == x_o[4] and 'X' == x_o[8],
'slant2_X' : 'X' == x_o[2] and 'X' == x_o[4] and 'X' == x_o[6]
}

and I want to check if any key gives True. How can I do it? Thx for help.

Joe
  • 69
  • 1
  • 8

3 Answers3

1

You can check if any of the dictionary values are true:

if True in x_wins.values():
  print("Success!")
else:
  print("All False...")

You could also use any like this: if any(x_wins.values()): ...

If you want to get the key for which the value is True then:

valid_keys = [key for key, val in x_wins.items() if val is True]

This will give the list of all keys that have a value of True.

geoph9
  • 357
  • 3
  • 18
1

You can use a list comprehension to find the "True" keys if I understand correctly:

true_keys = [x for x in x_wins if x_wins[x] == True]

Example:

x_o =['X','X','X',0,0,0,'X','X','X']
x_wins = {'row1_X': 'X' == x_o[0] and 'X' == x_o[1] and 'X' == x_o[2],
'row2_X' : 'X' == x_o[3] and 'X' == x_o[4] and 'X' == x_o[5],
'row3_X' : 'X' == x_o[6] and 'X' == x_o[7] and 'X' == x_o[8],
'col1_X' : 'X' == x_o[0] and 'X' == x_o[3] and 'X' == x_o[6],
'col2_X' : 'X' == x_o[1] and 'X' == x_o[4] and 'X' == x_o[7],
'col3_X' : 'X' == x_o[2] and 'X' == x_o[5] and 'X' == x_o[8],
'slant1_X' : 'X' == x_o[0] and 'X' == x_o[4] and 'X' == x_o[8],
'slant2_X' : 'X' == x_o[2] and 'X' == x_o[4] and 'X' == x_o[6]
}
true_keys = [x for x in x_wins if x_wins[x] == True]
print(true_keys)

Output:

['row1_X', 'row3_X']
Celius Stingher
  • 17,835
  • 6
  • 23
  • 53
0

You can do that with the any function.

The following will print win if any values of the x_wins dict is True :

if any(x_wins.values()):
    print('win!')
A-y
  • 793
  • 5
  • 16