How to group Python tuple elements by their first element?


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]]))

Updated on: 05-Mar-2020

496 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements