[英]add two dictionaries that are already inside a dictionary in each row of datframe
[英]Add two variables as values to an already created dictionary
我想append
两个变量到一个已经创建的字典的值。 准确地说,这两个变量 ( x
e y
) 需要为每场不同的曲棍球比赛相加,但问题是它们在最后都会单独相加,而不是在每场比赛中。
之前创建的字典工作正常,就是这样。 它由曲棍球比赛的名称和各种信息组成。
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])
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]],
现在我尝试像这样添加两个变量x
和y
:
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])
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]],
[1.75, 87.5], [2.5, 125.0]
我想得到类似的东西:
{'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]],
由于“行”变量,我相信第二个“for”语句在第一个语句中。
在那种情况下,您应该独立实施它,并使用“键”和“值”。
它应该是这样的:
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])
由于循环中有字典键,您可以使用它来将 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]])
或者
从字典项更新循环中的值
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.