How to group Python tuple elements by their first element?

PythonProgramming

Python has a function called defaultdict that groups Python tuple elements by their first element.

Example

lst = [
   (1, 'Hello', 'World', 112),
   (2, 'Hello', 'People', 42),
   (2, 'Hi', 'World', 200)
]

from collections import defaultdict

d = defaultdict(list)
for k, *v in lst:
   d[k].append(v)
print(d)

Output

This will give the output

defaultdict(<class 'list'>, {1: [['Hello', 'World', 112]], 2: [['Hello', 'People', 42], ['Hi', 'World', 200]]})

You can convert this back to tuples while keeping the grouping using the tuple(d.items()) method. 

example

print(tuple(d.items()))

Output

This will give the output

((1, [['Hello', 'World', 112]]), (2, [['Hello', 'People', 42], ['Hi', 'World', 200]]))
raja
Published on 18-Apr-2018 14:00:01
Advertisements