Summing up the values ​​in the list dictionary

I have a dictData dictionary that was created from 3 columns (0, 3 and 4) of the csv file, where each key is a datetime object, and each value is a list containing two numbers (let them name b, so the list is [a , b]) is saved as strings:

 import csv import datetime as dt with open(fileInput,'r') as inFile: csv_in = csv.reader(inFile) dictData = {(dt.datetime.strptime(rows[0],'%d/%m/%Y %H:%M')):[rows[3],rows[4]] for rows in csv_in} 

I want to do two things: firstly, I want to summarize each of the values ​​in the list (i.e., sum all the values ​​of a, and then sum all the values ​​of b) for the entire dictionary. If it were a dictionary with single values, I would do something like this:

 total = sum((float(x) for x in dictData.values())) 
  • How do I change this so that .values identifies the first (or second) element in the list? (i.e. a or b values)

  • I want to count all the null values ​​for the first item in a list.

+5
source share
2 answers

Customization

 dictData = {'2010': ['1', '2'], '2011': ['4', '3'], '2012': ['0', '45'], '2013': ['8', '7'], '2014': ['9', '0'], '2015': ['22', '1'], '2016': ['3', '4'], '2017': ['0', '5'], '2018': ['7', '8'], '2019': ['0', '9'], } print 'sum of 1st items = %d' % sum([float(v[0]) for v in dictData.values()]) print 'sum of 2nd items = %d' % sum([float(v[1]) for v in dictData.values()]) print 'count of zeros = %d' % sum([(float(v[0]) == 0) for v in dictData.values()]) sum of 1st items = 54 sum of 2nd items = 84 count of zeros = 3 
+8
source
 values = [(0,1), (2,3), (4,5)] values = np.array(values) print values[:, 0].sum() print values[:, 1].sum() print len([item for item in values[:, 0] if item == 0]) 
0
source

All Articles