Victor
Victor

Reputation: 133

Count number of values in nested lists inside a dictionary

I have the following dictionary:

d= {
'2018-01-01': [[1.0],        [2.0],        [3.0]],
'2018-01-02': [[4.0],        [5.0],        [6.0]],
'2018-01-03': [[7.0],        [8.0],        [9.0]],
'2018-01-04': [[10.0],       [11.0],       [12.0]],
'2018-01-31': [[13.0, 14.0], [15.0, 16.0], [17.0]]
}

My aim is to count the number of values (floats in this case), assuming some of these 'cells' might contain more than one value (e.g.: values for '2018-01-31'). In other words, I need:

result=17

So far, I was able to count the number of 'cells' (sublists), but I can't find out how can I count several values inside a single 'cell'. I tried:

cols=len(d[[k for k in d.keys() if d[k]==max(d.values(),key=len)][0]])
cells = [[1 for j in range(cols)] for i in range(len(d))]
result = len([item for sublist in cells for item in sublist])

print(str(result))

Output:

15

Thank you very much in advance.

Upvotes: 2

Views: 270

Answers (3)

jpp
jpp

Reputation: 164793

You do not need to create a flattened list for this task. This is one way:

from itertools import chain

res = sum(1 for _ in chain.from_iterable(map(chain.from_iterable, d.values())))

We deal with nested lists by applying chain.from_iterable twice and counting the results after this process.

Upvotes: 1

cs95
cs95

Reputation: 403020

Option 1
100% flattening + len

>>> len([k for i in d.values() for j in i for k in j])
17

Option 2
sum + len + partial flattening
Use a sum with a generator comprehension. 3-list form:

>>> sum(len([*a, *b, *c]) for (a, b, c) in d.values())
17

For a the generic solution (with more/less than 3 sublists), use itertools.chain:

>>> from itertools import chain
>>> sum(len(list(chain.from_iterable(v))) for v in d.values())
17

Upvotes: 2

fferri
fferri

Reputation: 18950

>>> len([c for a in d.values() for b in a for c in b])
17

you should really try these in an interactive interpreter, start from the simplest [x for x in d.values()] and work your way up.

Upvotes: 2

Related Questions