Sometimes, while working with data, we can be encountered with a situation in which we have list of list and we need to group it’s 2nd index with the common initial element in lists. Let’s discuss way in which this problem can be solved.
Method : Using defaultdict() + loop + dict()
The defaultdict can be used to initialize the group elements and loop can be used to group the values together and conversion to dictionary can be done using dict().
# Python3 code to demonstrate working of # Grouping list values into dictionary # Using defaultdict() + loop + dict() from collections import defaultdict # initializing list test_list = [['Gfg', 1], ['Gfg', 2], ['is', 3], ['best', 4], ['is', 5]] # printing original list print("The original list is : " + str(test_list)) # Grouping list values into dictionary # Using defaultdict() + loop + dict() temp = defaultdict(list) for key, val in test_list: temp[key].append(val) res = dict((key, tuple(val)) for key, val in temp.items()) # printing result print("The grouped dictionary is : " + str(res)) |
The original list is : [['Gfg', 1], ['Gfg', 2], ['is', 3], ['best', 4], ['is', 5]]
The grouped dictionary is : {'Gfg': (1, 2), 'best': (4, ), 'is': (3, 5)}
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.
Recommended Posts:
- Python - Summation Grouping in Dictionary List
- Python | Grouping dictionary keys by value
- Python - Frequency Grouping Dictionary
- Python - Convert List to key-value list by prefix grouping
- Python program to update a dictionary with the values from a dictionary list
- Python | Categorize tuple values into dictionary value list
- Python | Binary element list grouping
- Python | Grouping similar substrings in list
- Python | Identical Consecutive Grouping in list
- Python | Consecutive elements grouping in list
- Python | Frequency grouping of list elements
- Python - Value nested grouping on List
- Python - List Elements Grouping in Matrix
- Python - Convert Dictionary Value list to Dictionary List
- Python - Filter dictionary values in heterogenous dictionary
- Python - Append Dictionary Keys and Values ( In order ) in dictionary
- Python | Convert flattened dictionary into nested dictionary
- Python | Convert nested dictionary into flattened dictionary
- Python - Extract Dictionary values list to List
- Python - Assigning Key values to list elements from Value list Dictionary
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.

