Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Summing values in a dictionary of lists and counting all zero values for the first items in the lists

I have a dictionary dictData that has been created from 3 columns (0, 3 and 4) of a csv file where each key is a datetime object and each value is a list, containing two numbers (let's call them a and b, so the list is [a,b]) stored 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 sum each of the values in the list(i.e sum all the a values, then sum all the b values) for the whole dictionary. If it was a dictionary of single values, I would do something like this:

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

  2. I want to count all the zero values for the first item in the list.

like image 290
doctorer Avatar asked Feb 06 '23 13:02

doctorer


1 Answers

Setup

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
like image 155
piRSquared Avatar answered Feb 13 '23 07:02

piRSquared