A generator expression throws a large number of pairs of tuples, for example. as a list:
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 pass this stream of pairs to the dictionary to sum the values ββof the corresponding keys. The obvious solution:
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, can this be achieved with a generator expression or some similar construct that does not use a for loop?
EDIT
To clarify, the generator expression throws a large number of pairs of tuples:
(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 every pair of key values ββin the dictionary (see Paul McGuire's answer) as each pair is generated. The pairs = list [] operator was not superfluous and regretted it. For each pair (x, y), x is an integer, and y can be an integer or decimal / float.
My generator expression is:
((x,y) for y in something() for x in somethingelse())
and want to copy each pair (x, y) to defaultdict. Hth.