MikeR MikeR - 3 months ago 10x
Python Question

accessing values in a Dictionary of Lists

I have a dictionary

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 teh 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 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.



Setup dict

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

Various sums

[[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()])


Count zeros

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


If you used pandas

import pandas as pd

df = pd.DataFrame(dictData, dtype=float)

enter image description here

# sumation


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