简体   繁体   English

将两个变量作为值添加到已创建的字典中

[英]Add two variables as values to an already created dictionary

I would like to append two variables to the values of an already created dictionary.我想append两个变量到一个已经创建的字典的值。 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.准确地说,这两个变量 ( x e y ) 需要为每场不同的曲棍球比赛相加,但问题是它们在最后都会单独相加,而不是在每场比赛中。

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: output 是这样的:

{'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:现在我尝试像这样添加两个变量xy

 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. output 就是这个。 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]],

Because of the "row" variable, i believe that the second "for" statement are inside the first one.由于“行”变量,我相信第二个“for”语句在第一个语句中。

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

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.由于循环中有字典键,您可以使用它来将 x 和 y 的值添加到使用 .extend() 方法的列表值中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM