![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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]]))
Advertisements