【发布时间】:2023-03-07 21:17:01
【问题描述】:
我想在the dataset 中按月份、形状和参与者计算任何操作的数量。
这是我的代码
import csv
count_dict = dict()
with open(r'st2.csv',
mode = 'r') as csv_file:
lines = csv_file.readlines()
for row in lines:
data = row.split(',')
key = data[1] + '\t' + data[2] + '\t' + data[3][:7] + '\t' + data[4].strip()
if key in count_dict:
count_dict[key] += 1
else:
count_dict[key] = 1
print('\t'.join(['Name', 'Shape', 'Month', 'Action', 'Count']))
for element, count in count_dict.items():
items = element.split('\t')
activities = dict()
curdict = activities
for chunk in items:
curdict[chunk] = dict()
curdict = curdict[chunk]
for i in activities:
for k in activities[i]:
for l in activities[i][k]:
for m in activities[i][k][l]:
activities[i][k][l][m] = count
print(activities)
结果我得到了一系列的字典。
我怎样才能在一个具有这样结构的嵌套字典中计算这些值?
{'Googenhaim': {'Circle': {'2020-04': {'pin': 0, 'tap': 0, 'throw': 0, 'play': 1}, '2020-06': {'pin': 0, 'tap': 0, 'throw': 0, 'play': 1}, '2020-05': {'pin': 0, 'tap': 0, 'throw': 0, 'play': 1}}, 'Rectangle': {'2020-04': {'pin': 0, 'tap': 0, 'throw': 0, 'play': 1}, '2020-06': {'pin': 0, 'tap': 0, 'throw': 0, 'play': 1}, '2020-05': {'pin': 0, 'tap': 0, 'throw': 0, 'play': 1}}, 'Trapezoid': {'2020-04': {'pin': 0, 'tap': 0, 'throw': 0, 'play': 1}, '2020-06': {'pin': 0, 'tap': 0, 'throw': 0, 'play': 1}
【问题讨论】:
标签: python csv count readlines