每当键重复时,从CSV文件创建的Python字典应合并值(整数)
我有一个名为每当键重复时,从CSV文件创建的Python字典应合并值(整数),python,csv,dictionary,Python,Csv,Dictionary,我有一个名为report\u data.csv的文件,其中包含以下内容: user,score a,10 b,15 c,10 a,10 a,5 b,10 我正在使用以下代码从此文件创建一个词典: with open('report_data.csv') as f: f.readline() # Skip over the column titles mydict = dict(csv.reader(f, delimiter=',')) 运行此代码后,mydict为: mydic
report\u data.csv
的文件,其中包含以下内容:
user,score
a,10
b,15
c,10
a,10
a,5
b,10
我正在使用以下代码从此文件创建一个词典
:
with open('report_data.csv') as f:
f.readline() # Skip over the column titles
mydict = dict(csv.reader(f, delimiter=','))
运行此代码后,mydict
为:
mydict = {'a':5,'b':10,'c':10}
但我希望它是:
mydict = {'a':25,'b':25,'c':10}
换句话说,每当在读取文件行时遇到
mydict
中已经存在的键时,mydict
中与该键相关联的新值应该是旧值和文件行上显示的整数之和。我怎样才能做到这一点?这应该适合您:
with open('report_data.csv') as f:
f.readline()
mydict = {}
for line in csv.reader(f, delimiter=','):
mydict[line[0]] = mydict.get(line[0], 0) + int(line[1])
最简单的方法是使用有用模块中的
defaultdict
或Counter
Counter
类中最有用的功能之一是most_common()
mydict = {}
with open('report_data.csv') as f:
f.readline()
x = csv.reader(f, delimiter=',')
for x1 in x:
if mydict.get(x1[0]):
mydict[x1[0]] += int(x1[1])
else:
mydict[x1[0]] = int(x1[1])
print mydict
关于在Python[,]中从CSV聚合数据,前面有很多问题。
mydict = {}
with open('report_data.csv') as f:
f.readline()
x = csv.reader(f, delimiter=',')
for x1 in x:
if mydict.get(x1[0]):
mydict[x1[0]] += int(x1[1])
else:
mydict[x1[0]] = int(x1[1])
print mydict