Is it possible to access current object while doing list/dict comprehension in Python?

No, there is not. A dict comprehension produces a new item for each iteration, and your code needs to produce fewer items (consolidating values).

There is no way to access keys produced in an earlier iteration, not without using (ugly, unpythonic) side-effect tricks. The dict object that is going to be produced by the comprehension doesn’t exist yet, so there is no way to produce a self-reference either.

Just stick to your for loop, it is far more readable.

The alternative would be to use sorting and grouping, a O(NlogN) algorithm vs. the simple O(N) of your straight loop:

from itertools import groupby
from operator import itemgetter

res = {key: sum(t[1] for t in group) 
       for key, group in groupby(sorted(data, key=itemgetter(0)), key=itemgetter(0))}

Leave a Comment