I would like to append
two variables to the values of an already created dictionary. Precisely these two variables (x
e y
) need to add up for each different hockey game, but the problem is that they all add up separately at the end and aren't inside every game.
The dictionary created earlier works fine and this is it. It consists of the name of the hockey matches and various info.
my_dict= {}
for row in mydb.fetchall():
if row[0] not in my_dict:
#I create dictionary
my_dict[row[0]] = list(row[1:])
my_dict[row[0]][4] = [my_dict[row[0]][4]] # transform int to list of int
else:
my_dict[row[0]][4].append(row[5])
The output is this:
{'Dallas-Minnesota': ['NHL', 8.1, 9, '15:00', [0, 1, 1, 5]],
'Vegas-New York': ['NHL', 8.1, 9, '18:00', [1, 2, 3, 4]],
Now I try to add the two variables x
and y
like this:
for key, value in my_dict.items():
#two variables
x= sum(value[4]) / len(value[4])
y = (x *100) / 2
#add values to dictionary
my_dict[row[0]].append([x], [y])
The output is this. As you can see the new values are separated and added at the end:
{'Dallas-Minnesota': ['NHL', 8.1, 9, '15:00', [0, 1, 1, 5]],
'Vegas-New York': ['NHL', 8.1, 9, '18:00', [1, 2, 3, 4]],
[1.75, 87.5], [2.5, 125.0]
I would like to get something like:
{'Dallas-Minnesota': ['NHL', 8.1, 9, '15:00', [0, 1, 1, 5], [1.75], [87.5]],
'Vegas-New York': ['NHL', 8.1, 9, '18:00', [1, 2, 3, 4], [2.5], [125.0]],
CodePudding user response:
Because of the "row" variable, i believe that the second "for" statement are inside the first one.
In that case you should implement it independently, and use the "key" and "value".
It should be something like this:
for key, value in my_dict.items():
#two variables
x= sum(value[4]) / len(value[4])
y = (x *100) / 2
#add values to dictionary
my_dict[key].append([x])
my_dict[key].append([y])
CodePudding user response:
Since you have the dictionary key in the loop, you can use it to to add the values of x and y to the list value using .extend() method.
for key, value in my_dict.items():
#two variables
x= sum(value[4]) / len(value[4])
y = (x *100) / 2
#add values to dictionary
my_dict[key].extend([[x], [y]])
OR
Update the value in the loop from the dictionary items
for key, value in my_dict.items():
#two variables
x= sum(value[4]) / len(value[4])
y = (x *100) / 2
#add values to dictionary
value.extend([[x], [y]])