问题描述
我不太确定是否曾经问过这个问题,但是...将字典值添加到字典中的“值”后,我需要帮助来更新字典值。 请帮忙!
import csv
with open('USVideos.csv', encoding="utf-8") as file:
reader = csv.reader(file, delimiter=',')
header = next(reader)
youtube_usa_videos = []
for row in reader:
youtube_usa_videos.append(row)
Unique_channels = []
for list in youtube_usa_videos:
if list[2] in Unique_channels:
continue
else:
Unique_channels.append(list[2])
Like_per_channel = dict((channel, 0) for channel in Unique_channels)
for (key, value) in Like_per_channel.items():
for list in youtube_usa_videos:
if list[2] == key:
value += int(list[7])
else:
continue
print(Like_per_channel)
找到要增加的值的唯一键后,如何更新“ Like_per_channel.items()”中的值?
谢谢!
1楼
代替:
if list[2] == key:
value += int(list[7])
采用:
if list[2] == key:
Like_per_channel[key] += int(list[7])
更新正在遍历的字典不是一个好主意。 您可以创建一个副本并更新它。