class Players:
def __init__(self, username, score):
self.username = username
self.score = score
If I create a class and some instances of it with different scores, how can I get a dictionary with the username as key and the score as value for all instances? I will change the score after creating the instance, so appending score and username to the dictionary when creating the instance can not work.
thank you so much
CodePudding user response:
A tricky way is to use attrgetter
from operator
from operator import attrgetter
p1 = Players('p1', 10)
p2 = Players('p2', 11)
p3 = Players('p3', 12)
instances = [p1, p2, p3]
d = dict(map(attrgetter('username', 'score'), instances))
print(d)
# {'p1': 10, 'p2': 11, 'p3': 12}
or without any extra imports
d = dict((obj.username, obj.score) for obj in instances)
CodePudding user response:
As an easiest way, you can do
player_instance = Player("name", 0)
...
player_instance.__dict__
This dictionary is also linked to the object, so changes to the dictionary will change the instance
player_instance.__dict__["score"] = 123456789
# player_instance.score is now 123456789
Though, you don't necessarily want to have your object accept changes though this dictionary. Generally what you would usually do is make a method that generates your desired data structure for you
class Players:
def __init__(self, username, score):
self.username = username
self.score = score
@property
def as_dict(self):
return {"username": self.username, "score": self.score}