MikeR - 3 months ago 10x

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 summ 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 this:

`total = sum([float(x) for x in dictData.values()])`

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

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

Thanks!

Answer

```
dictData = {'2014': ['1', '2'],
'2015': ['0', '3']}
```

```
[[float(x) for x in v] for v in dictData.values()]
[[0.0, 3.0], [1.0, 2.0]]
[sum([float(x) for x in v]) for v in dictData.values()]
[3.0, 3.0]
sum([sum([float(x) for x in v]) for v in dictData.values()])
6.0
```

```
sum([float(v[0]) == 0 for v in dictData.values()])
1
```

```
import pandas as pd
df = pd.DataFrame(dictData, dtype=float)
df
```

```
# sumation
df.sum().sum()
6.0
# count zeroes in first position
(df.loc[0, :] == 0).sum()
1
```

Source (Stackoverflow)

Comments