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 a for loop and conditional statements

This method involves using a for loop to iterate over the list of tuples. We will 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 will create a new key−value pair in the dictionary.

Syntax

list_name.append(element)

Here, the append() function is a list method used to add an element to the end of the list_name. It modifies the original list by adding the specified element as a new item.

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. For each tuple, we extract the key and value using indexing. If the key already exists in the result dictionary, we append the value to the existing list associated with that key. Otherwise, we create a new key−value pair in the result dictionary, with the key as the extracted key and the value as a list containing the extracted value. Finally, we print the resulting dictionary.

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)

Output

{'apple': [5, 2], 'banana': [3, 1], 'cherry': [7]}

Method 2: Using the defaultdict class from the 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.

Syntax

groups = defaultdict(list)

Here, the syntax initializes a defaultdict object called groups with a default value of an empty list using the defaultdict() function from the collections module. The second line of code uses the key (item) to access the list associated with that key in the groups dictionary and appends the item to the list.

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. The rest of the code is similar to the first method, where we iterate over each tuple in the data list, extract the key and value, and append the value to the corresponding key in the result dictionary. Finally, we convert the result defaultdict to a regular dictionary using the dict() function before printing.

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

Output

{'apple': [5, 2], 'banana': [3, 1], 'cherry': [7]}

Method 3: Using the groupby() function from the itertools module

This method involves utilizing the groupby() function from the itertools module. The groupby() function groups the elements of an iterable based on a key function.

Syntax

 groups[key] = list(group)

Here, the groupby() function from the itertools module iterates over the groupby object. The function returns both the key and a group of consecutive items with the same value. The key and group are then used to create a key−value pair in the groups dictionary, where the key is the unique value and the value is the list of grouped items.

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. We then iterate over the groups generated by groupby(). For each group, we extract the key and create a list of values associated with that key. Finally, we store the key−value pair in the result dictionary and print it.

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)

Output

{'apple': [5, 2], 'banana': [3, 1], 'cherry': [7]}

Conclusion

In this article, we discussed how we can group list of tuples to a dictionary using various method in Python. We explored three methods: using a for loop and conditional statements, using the defaultdict class from the collections module, and utilizing the groupby() function from the itertools module. Each method provides a solution to the task, and the choice depends on personal preference and specific requirements.

Updated on: 19-Jul-2023

210 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements