Python | Group by matching second tuple value in list of tuples
Given a list of tuples, the task is to group the tuples by matching the second element in the tuples. We can achieve this using dictionary by checking the second element in each tuple.
Examples:
Input : [(20, 80), (31, 80), (1, 22), (88, 11), (27, 11)]
Output: {80: [(20, 80), (31, 80)],
11: [(88, 11), (27, 11)],
22: [(1, 22)]}
Input : [(20, 'Geek'), (31, 'Geek'), (88, 'NotGeek'), (27, 'NotGeek')]
Output: {'NotGeek': [(88, 'NotGeek'), (27, 'NotGeek')],
'Geek': [(20, 'Geek'), (31, 'Geek')]}
Code #1:
# Python program to group tuples by matching # second tuple value in list of tuples # Initialisation Input = [(20, 80), (31, 80), (1, 22), (88, 11), (27, 11)] Output = {} for x, y in Input: if y in Output: Output[y].append((x, y)) else: Output[y] = [(x, y)] # Printing Output print(Output) |
chevron_right
filter_none
Output:
{80: [(20, 80), (31, 80)], 11: [(88, 11), (27, 11)], 22: [(1, 22)]}
Code #2:
# Python program to group tuples by matching # second tuple value in list of tuples # Initialisation Input = [(20, 'Geek'), (31, 'Geek'), (88, 'NotGeek'), (27, 'NotGeek')] Output = {} for x, y in Input: if y in Output: Output[y].append((x, y)) else: Output[y] = [(x, y)] # Printing Output print(Output) |
chevron_right
filter_none
Output:
{'NotGeek': [(88, 'NotGeek'), (27, 'NotGeek')],
'Geek': [(20, 'Geek'), (31, 'Geek')]}
Recommended Posts:
- Python | Group tuples in list with same first value
- Python program to create a list of tuples from given list having number and its cube in each tuple
- Python | Reverse each tuple in a list of tuples
- Python | Swap tuple elements in list of tuples
- Python | Remove tuple from list of tuples if not containing any character
- Python | Remove matching tuples
- Python | Check if element is present in tuple of tuples
- Python | Remove tuples from list of tuples if greater than n
- Python | Find the tuples containing the given element from a list of tuples
- Python | Count tuples occurrence in list of tuples
- Python | Remove tuples having duplicate first value from given list of tuples
- Python | Remove duplicate tuples from list of tuples
- Python | Combining tuples in list of tuples
- Python | Sort tuple list by Nth element of tuple
- Python | Convert list of tuples to list of strings
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



