You can use a dictionary to store the values for each key. Then, make a list of lists from the dictionary elements.
data = [['a', 3], ['b', 2], ['b', 1.1], ['c', 5],['c', 1.2]]
mapper = {}
for pair in data:
key, val = pair
mapper[key] = mapper.get(key, 0) + val
data_merged = list(map(list, mapper.items()))
print(data_merged)
Output:
[['a', 3], ['b', 3.1], ['c', 6.2]]
Explanation:
- Declares an empty dictionary (
mapper).
- Iterates each pair of elements.
- If the key is already in the dictionary then increase it by given value. Otherwise, set it is as the initial value.
- Creates a list of lists from the dictionary items.