A generator expression is throwing off a large number of tuple pairs eg. in list form:
pairs = [(3, 47), (6, 47), (9, 47), (6, 27), (11, 27), (23, 27), (41, 27), (4, 67), (9, 67), (11, 67), (33, 67)]
For each pair in pairs, with key = pair[0] and value = pair[1], I want to feed this stream of pairs into a dictionary to cumulatively add the values for the respective keys. The obvious solution is:
dict_k_v = {}
for pair in pairs:
try:
dict_k_v[pair[0]] += pair[1]
except:
dict_k_v[pair[0]] = pair[1]
>>> dict_k_v
{33: 67, 3: 47, 4: 67, 6: 74, 9: 114, 11: 94, 41: 27, 23: 27}
However, could this be achieved with a generator expression or some similar construct that doesn’t use a for-loop?
EDIT
To clarify, the generator expression is throwing off a large number of tuple pairs:
(3, 47), (6, 47), (9, 47), (6, 27), (11, 27), (23, 27), (41, 27), (4, 67), (9, 67), (11, 67), (33, 67) …
and I want to accumulate each key-value pair into a dictionary (see Paul McGuire’s answer) as each pair is being generated. The pairs = list[] statement was unnecessary and sorry about that. For each pair (x,y), x is an integer and y can be an integer or decimal/float.
My generator expression is of the form:
((x,y) for y in something() for x in somethingelse())
and want to accumulate each (x,y) pair into a defaultdict. Hth.