I’m still new to Python. I have similar list to the below list:
items = [[4, 'A'], [4, 'B'], [5, 'C'], [5, 'D'], [5, 'E'], [6, 'F'], [6, 'G']]
I’m trying to print it by grouping the first item together and get something like this:
4 : ['A', 'B'] 5 : ['C', 'D', 'E'] 6 : ['F', 'G']
How do I do this?
Advertisement
Answer
You can use itertools.groupby and operator.itemgetter:
>>> from itertools import groupby
>>> from operator import itemgetter
>>> list_ = [[4, 'A'], [4, 'B'], [5, 'C'], [5, 'D'], [5, 'E'], [6, 'F'], [6, 'G']]
>>> print(*(f'{k}: {sum(list(g), [])}'
for k, g in groupby(list_, key=lambda x: list.pop(x, 0))),
sep='n')
4: ['A', 'B']
5: ['C', 'D', 'E']
6: ['F', 'G']
If you want to do this without importing anything:
>>> list_ = [[4, 'A'], [4, 'B'], [5, 'C'], [5, 'D'], [5, 'E'], [6, 'F'], [6, 'G']]
>>> table = {}
>>> for key, value in list_:
table.setdefault(key, []).append(value)
>>> table
{4: ['A', 'B'], 5: ['C', 'D', 'E'], 6: ['F', 'G']}
>>> for key, group in table.items():
print(f'{key}: {group}')
4: ['A', 'B']
5: ['C', 'D', 'E']
6: ['F', 'G']