Home > database >  How can i insert a variable in a dictionary created with a class?
How can i insert a variable in a dictionary created with a class?

Time:01-15

I would like to save the variable x in the dictionary and consequently print it for each element of the loop.

I use this code test[row[0]].score_home.append(x). I would like to insert it as the last value (right after score_away=[]).

P.S: I don't want to store multiple values of x in the dictionary. Each match has an x. Each x has only one value (only 1)

I get this error: AttributeError: 'NoneType' object has no attribute 'append'

{'Minnesota-Vegas': Info_Matchs(championship='NHL', date=8.1, current_round=9, clock='15:00', score_home=[0, 1, 1, 5], score_away=[])

I would like to get this output as a result:

{'Minnesota-Vegas': Info_Matchs(championship='NHL', date=8.1, current_round=9, clock='15:00', score_home=[0, 1, 1, 5], score_away=[], x=1.75)

Code

test = {}

@dataclass
class Info_Matchs:
    championship: str
    date: float
    round: int
    clock: str
    score_home: list[int]
    score_away: list[int]
    x: float

db = cursor_test.execute('''SELECT Next.team_home||"-"||Next.team_away, Next.tournmant,
                                                  Next.date, Next.round, Next.time,
                                                  Results.score_home
                                           FROM Next
                                           INNER JOIN Results
                                           ON Next.team_home = Results.team_home;''')
    

for row in db.fetchall():
    if row[0] not in test:
        info = Info_Matchs(
            championship=row[1],
            date=row[2],
            current_round=row[3],
            clock=row[4],
            score_home=list(),
            score_away=list(),
            x=None)

        test[row[0]] = info
    test[row[0]].score_home.append(row[5])

#HERE
for key, value in test.items():
    calc = sum(value.score_home)

    test[row[0]].x.append(calc)

    print(test)

CodePudding user response:

info = Info_Matchs(
    championship=row[1],
    date=row[2],
    current_round=row[3],
    clock=row[4],
    score_home=list(),
    score_away=list(),
    x=None)

Here you are assigning x as None value and then you're trying to treat that None value as a list by appending to it.

Instead of doing this:

test[row[0]].x.append(calc)

Assign a new value to the x:

test[key].x = calc
  • Related