How do I set parameters of objects saved in a list class without looping?

60 Views Asked by At

I have 1 main class and one class, that functions as a storage list for every object created, so I can keep track of every newly created user.

But how can I access the parameters of a user in that list via a "username", so I can get and set each single one of an objects parameter within that list?

Or is there a way smoother solution to keep oversight over thousands of users?

import os
from dotenv import load_dotenv, find_dotenv
#from src import log
from attrs import validators, setters
from attrs import define, frozen, field, Factory

from typing import List
from cattrs import structure

@define(slots = True)
class User:

    username: str = field(validator=validators.instance_of(str))
    discordid: int = field(validator=validators.instance_of(int))
    roles: list = field(default=[])
    experience: int = field(validator=validators.instance_of(int), default=0)
    user_wins: dict = field(validator=validators.instance_of(dict), default={})

@define
class UserList:
    users: List[User] = field(factory=list)

d = {
    "users": [
        {"username": "Duffy", "discordid": 1233, "roles": ["hi"]},
        {"username": "Bugs", "discordid": 124124, "roles": ["hi"]},
        {"username": "Sylvester", "discordid": 12414, "roles": ["hi"]},
        {"username": "Elmar", "discordid": 4444, "roles": ["hi"]},
        {"username": "Tweety", "discordid": 1111, "roles": ["hi"]},
        {"username": "Sam", "discordid": 12331, "roles": ["hi"]},
        {"username": "Wile E.", "discordid": 11, "roles": ["hi"]},
        {"username": "Road", "discordid": 1, "roles": ["hi"]},
    ]
}

username = "Elmar"    # example user name, I'd like to retrieve
c = structure(d, UserList) # c = list of user objects, initialized via d

# Set user value in object & list?
?????????

I'm confused with how get/set variables are constructed via attrs and I'm out of any idea how I could access the user via a getter/setter in the UserList class.

My getters/setters both in UserList & Users were wrong and I assume I have an error in my logic.

Tried to access the list via the index of the user, but it failed.

userNameXposition = {}

for i in range(0, len(d["users"])):
    username = d["users"][i]["username"]
    userNameXposition[username] = i

discord_id = c[userNameXposition[username]]
0

There are 0 best solutions below