Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python - Group list of Tuples to Dictionary
In Python, we can group list of tuples to a dictionary using different methods like using a for loop and conditional statements, using the defaultdict class from the collections module, and using the groupby() function from the itertools module. In this article we will explore all these methods and implement them to group a list of tuples to dictionary.
Method 1: Using For Loop and Conditional Statements
This method involves using a for loop to iterate over the list of tuples. We check if the key exists in the dictionary and add the corresponding tuple as a value to that key. If the key does not exist, we create a new key?value pair in the dictionary.
Example
In the below example, we have a list of tuples named data. We initialize an empty dictionary named result. We iterate over each tuple in the data list using a for loop ?
data = [('apple', 5), ('banana', 3), ('apple', 2), ('cherry', 7), ('banana', 1)]
result = {}
for item in data:
key = item[0]
value = item[1]
if key in result:
result[key].append(value)
else:
result[key] = [value]
print(result)
The output of the above code is ?
{'apple': [5, 2], 'banana': [3, 1], 'cherry': [7]}
Method 2: Using defaultdict from Collections Module
This method uses the defaultdict class from the collections module. The defaultdict provides a default value for a nonexistent key, making it convenient for grouping data.
Example
In the below example, we import the defaultdict class from the collections module. We initialize the result variable as a defaultdict with the default value set as an empty list ?
from collections import defaultdict
data = [('apple', 5), ('banana', 3), ('apple', 2), ('cherry', 7), ('banana', 1)]
result = defaultdict(list)
for item in data:
key = item[0]
value = item[1]
result[key].append(value)
print(dict(result))
The output of the above code is ?
{'apple': [5, 2], 'banana': [3, 1], 'cherry': [7]}
Method 3: Using groupby() from Itertools Module
This method utilizes the groupby() function from the itertools module. The groupby() function groups the elements of an iterable based on a key function.
Example
In the below example, we import the groupby() function from the itertools module. Before using groupby(), we sort the data list based on the key using a lambda function. This step is crucial because groupby() expects consecutive elements with the same key to be adjacent in the iterable ?
from itertools import groupby
data = [('apple', 5), ('banana', 3), ('apple', 2), ('cherry', 7), ('banana', 1)]
result = {}
data.sort(key=lambda x: x[0]) # Sort the data based on the key
for key, group in groupby(data, key=lambda x: x[0]):
result[key] = [item[1] for item in group]
print(result)
The output of the above code is ?
{'apple': [5, 2], 'banana': [3, 1], 'cherry': [7]}
Comparison
| Method | Complexity | Best For | Requires Sorting |
|---|---|---|---|
| For Loop | Simple | Basic understanding | No |
| defaultdict | Clean | Professional code | No |
| groupby() | Advanced | Pre?sorted data | Yes |
Conclusion
We explored three methods to group list of tuples into dictionaries. Use defaultdict for clean, professional code. Use groupby() when data is already sorted. Use basic for loop for simple scenarios.
