Reputation: 205
Im attempting to write a chess 'Swiss' tournament manager in Python. I have two classes, a match class and a player class. I also have two dictionaries, name_object, which binds a string name to an object, and name_score, which binds the Player object's name to the Player object's score (1.0, 2.5 etc.).
Variable Example
name_object = {'Jim' : Object, 'Jack' : Object}
name_score = {'Jim': 2.5, 'Jack' : 1.0}
My Classes
class Player:
def __init__(self, name, gender, rating, score):
self.name = name
self.gender = gender
self.rating = rating
self.score = score
class Match:
def __init__(self, white, black):
self.white = white
self.black = black
def Result(self, res):
global name_object, name_score
complete = False
if res == 1:
if complete == False:
name_object[self.white].score += 1
name_score[self.white] += 1
complete = True
elif res == 0:
if complete == False:
name_object[self.black].score += 1
name_score[self.black].score += 1
complete = True
elif res == 'd':
if complete == False:
name_object[self.white].score += .5
name_score[self.white] += .5
name_object[self.black].score += .5
name_score[self.black].score += .5
but when I try to create an object with the two player names of 'Jim' and 'Jack',
Match1 = Match(name_object['Jim'], name_object['Jack'])
and then try to call the Result method with white winning,
Match1.Result(1)
I get this error,
line 43, in Result
name_object[self.white].score += 1
KeyError: <__main__.Player object at 0x02AB6DF0>
All help is much appreciated
Upvotes: 2
Views: 5004
Reputation: 70602
By eyeball, your name_object
dict has strings for keys ('Jim'
and 'Jack'
). But your
name_object[self.white].score += 1
line (the one Python is complaining about) is not using a string to index name_object
. It's using name_object['Jim']
(which is the undefined-in-the-code-you've-shown Object
) to index that dict. That's why you're getting the KeyError
: you're trying to index the dict using a key that's not in the dict.
How you fix it is up to you. I can't guess whether you want to use strings or instances of Player
to index your dict.
Upvotes: 0
Reputation: 60147
self.white
is set to name_object['Jim']
, so when you do name_object[self.white]
you are in effect searching the dict like
name_object[name_object['Jim']]
I very much doubt that that makes sense. You might want to consider passing 'Jim'
alone in as self.white
and then using name_object[self.white]
in the rest of your code as appropriate.
Upvotes: 2