![](/img/trans.png)
[英]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.