MikeR - 7 months ago 30

Python Question

I have a dictionary

`dictData`

`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()))`

- How do I change this so that identifies the first (or second) item in the list? (i.e. the a or b values)
`.values`

- I want to a count of all the zero values for the first item in the list.

Answer

```
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
```