Group Keys to Values List Using Python


Grouping keys to values is the process of categorizing data based on specific attributes or criteria. For example, imagine you have a dataset of students, and you want to group them by their grades. This grouping allows us to easily analyze and perform computations on each category separately. In Python, we can Group keys to values list in various ways like using dictionaries, defaultdict, and itertools.groupby. In this article, we will understand how we can Group keys to a Values list using these methods.

Method 1:Using Dictionaries

We can easily group keys to values using dictionaries in Python. Let's consider an example where we have a list of fruits, and we want to group them based on their colors.

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 iterate over the list of fruits and extract the color for each fruit. We then check if the color already exists in the grouped_fruits dictionary. If it does, we append the fruit to the existing list of fruits for that color. Otherwise, we create a new list with the current fruit and assign it to the corresponding color.

fruits = [
    {"name": "Apple", "color": "Red"},
    {"name": "Banana", "color": "Yellow"},
    {"name": "Grapes", "color": "Green"},
    {"name": "Orange", "color": "Orange"},
    {"name": "Blueberry", "color": "Blue"},
    {"name": "Strawberry", "color": "Red"},
]

grouped_fruits = {}

for fruit in fruits:
    color = fruit["color"]
    if color in grouped_fruits:
        grouped_fruits[color].append(fruit)
    else:
        grouped_fruits[color] = [fruit]

print(grouped_fruits)

Output

{
    'Red': [{'name': 'Apple', 'color': 'Red'}, {'name': 'Strawberry', 'color': 'Red'}],
    'Yellow': [{'name': 'Banana', 'color': 'Yellow'}],
    'Green': [{'name': 'Grapes', 'color': 'Green'}],
    'Orange': [{'name': 'Orange', 'color': 'Orange'}],
    'Blue': [{'name': 'Blueberry', 'color': 'Blue'}]
}

Method 2:Grouping with defaultdict

We can implement a more effective solution using defaultdict from the Python collections module. The defaultdict automatically initializes a value for a non-existing key, saving us from the need to explicitly check and create lists.

Syntax

groups = defaultdict(list)
groups[item].append(item)

Here, the defaultdict(list) creates a dictionary-like object called groups using the defaultdict class from the collections module. The groups[item].append(item) appends an item to the list associated with the key item in the groups dictionary. By using square brackets [] to access the dictionary with groups[item], it either retrieves the existing list if the key item already exists, or creates a new empty list as the value if item is encountered for the first time.

Example

In the below example, we create a defaultdict called grouped_fruits, and its default value is set to an empty list using defaultdict(list). Now, whenever we access a non-existing key, it automatically initializes an empty list as the value. This simplifies the grouping process, as we don't need to handle key existence seperately.

from collections import defaultdict
fruits = [
    {"name": "Apple", "color": "Red"},
    {"name": "Banana", "color": "Yellow"},
    {"name": "Grapes", "color": "Green"},
    {"name": "Orange", "color": "Orange"},
    {"name": "Blueberry", "color": "Blue"},
    {"name": "Strawberry", "color": "Red"},
]

grouped_fruits = defaultdict(list)

for fruit in fruits:
    grouped_fruits[fruit["color"]].append(fruit)

print(dict(grouped_fruits))

Output

{
    'Red': [{'name': 'Apple', 'color': 'Red'}, {'name': 'Strawberry', 'color': 'Red'}],
    'Yellow': [{'name': 'Banana', 'color': 'Yellow'}],
    'Green': [{'name': 'Grapes', 'color': 'Green'}],
    'Orange': [{'name': 'Orange', 'color': 'Orange'}],
    'Blue': [{'name': 'Blueberry', 'color': 'Blue'}]
}

Method 3:Grouping with itertools.groupby

We can use the groupby function from the itertools module of Python to group keys to value easily. This function allows us to group elements in an iterable based on a key function.

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.

itertools.groupby(iterable, key=None)

Here, the groupby() method takes an iterable as input and an optional key function. It returns an iterator that generates tuples containing consecutive keys and groups from the iterable. The key function is used to determine the grouping criterion.

Example

In the below example, we define a key function called key_function, which categorizes the numbers as "Even" or "Odd" based on their parity. We then use groupby to group the numbers based on this key function. The groupby function returns an iterator that provides the key and an iterator of the grouped elements. We convert the iterator to a list and assign it as the value in the grouped_numbers dictionary.

from itertools import groupby

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

grouped_numbers = {}
key_function = lambda x: "Even" if x % 2 == 0 else "Odd"

for key, group in groupby(numbers, key_function):
    grouped_numbers[key] = list(group)

print(grouped_numbers)

Output

{'Odd': [9], 'Even': [10]}

Conclusion

In this article, we discussed how we can group keys to values list using different method in Python. We started with using dictionaries, where we manually checked for key existence and created lists as values. Then, we used defaultdict, which simplified the grouping process by automatically initializing values for non-existing keys. Also, we explored itertools.groupby, a powerful function that allows grouping based on a key function.

Updated on: 17-Jul-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements