python - List of list increment if exists otherwise extend -
i have list of lists follows
[ ['a', 1], ['b',2], ['c',1], ['a', 2], ['c', 5] ]
i want normalize list in such way every, 'a', 'b', 'c' etc, have 1 unique entry in list, , every duplicate list, second value quantity added like:
[ ['a', 3], # since 'a' existed quantity added 1 + 2 becomes 3 ['b',2], ['c',6] # 'c' becomes 1 + 5 = 6 ]
how python ?
i'd suggest use collections.defaultdict()
below:
from collections import defaultdict l = [ ['a', 1], ['b',2], ['c',1], ['a', 2], ['c', 5] ] d = defaultdict(int) key, value in l: d[key] += value print(d.items())
output:
dict_items([('b', 2), ('a', 3), ('c', 6)])
also can use try...expect
instead of collections.defaultdict()
...if you'd like:
d = {} key, value in l: try: d[key] += value except keyerror: d[key] = value
also, can try if...else
:
d = {} key, value in l: if key in d: d[key] += value else: d[key] = value
Comments
Post a Comment