Search code examples
pythondictionaryinstance

get a dictionary of an attribute in all instances


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


Solution

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