MattE MattE - 2 months ago 7
Python Question

Merge list of lists where index0 values match?

I have a list of lists and I want to merge them to sum the inner index[1] values where the index[0] values match. My list looks like this:

lists = [
['Gifts', [4]],
['Gifts', [4]],
['Politics', [3]],
['Supply', [4]],
['Supply', [4]],
['Prints', [1]],
['Prints', [1]],
['Prints', [1]],
['Politics', [3]],
['Politics', [3]],
['Accounts', [2]],
['Accounts', [2]],
['Accounts', [2]],
['Features', [3]],
['Features', [2]]
]


I would therefore like the new structure to be:

new_lists = [
[Gifts', 8], ['Politics', 9], ['Supply', 8], ['Prints', 3], ['Accounts', 6], ['Features', 5]
]


How do I achieve this in python?

Answer

You can use defaultdict(int) from collections module:

>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for key, value in lists:
...     d[key] += value[0]
... 
>>> dict(d)
{'Gifts': 8, 'Prints': 3, 'Accounts': 6, 'Features': 5, 'Supply': 8, 'Politics': 9}
>>> list(d.items())
[('Prints', 3), ('Features', 5), ('Supply', 8), ('Gifts', 8), ('Accounts', 6), ('Politics', 9)]