I have an array of arrays, like this...
[[\'Abradolf Lincler\', 4], [\'Abradolf Lincler\', 4], [\'Scary Terry\', 4], [\'Abradolf Lincler\', 4], [\'Scary Terry\',
Better using setdefault
:
d={}
for x,y in arrays:
d.setdefault(x,[]).append(y)
print(list(map(list,{k:sum(v) for k,v in d.items()}.items())))
Output:
[['Abradolf Lincler', 32], ['Scary Terry', 20], ['Summer Smith', 20]]
Best in all defaultdict
:
from collections import defaultdict
d=defaultdict(int)
for x,y in arrays:
d[x]+=y
print(list(map(list,dict(d).items())))
Output:
[['Abradolf Lincler', 32], ['Scary Terry', 20], ['Summer Smith', 20]]