Trying to think of a one-liner to achieve the following ( summing all the values of a key) :
>>> data = [('a',1),('b',3),('a',4),('c',9),('b',1),('d',3)]
>>> res = {}
>>> for tup in data:
... res[tup[0]] = res.setdefault(tup[0],0) + tup[1]
...
>>> res
{'a': 5, 'c': 9, 'b': 4, 'd': 3}
One-liner version without using any imports like itertools,collections etc.
{ tup[0] : SELF_REFERENCE.setdefault(tup[0],0) + tup[1] for tup in data }
Is it possible in Python to use a reference to the object currently being comprehended ? If not, is there any way to achieve this in a one-liner without using any imports i.e. using basic list/dict comprehension and inbuilt functions.
SELF_REFERENCE
is under construction, in the comprehension :) - thefourtheyesum((Counter(dict([x])) for x in data), Counter())
instead... - wim