py4u blog

Python Program to Group Keys with Similar Values in a Dictionary

In Python, dictionaries are a powerful data structure that allow us to store key-value pairs. Sometimes, we may encounter a situation where we need to group keys that have similar values. This can be useful in various scenarios, such as data analysis, where we want to categorize data based on certain criteria. In this blog post, we will explore different ways to group keys with similar values in a dictionary using Python.

2026-06

Table of Contents#

Using a Default Dictionary#

The defaultdict class from the collections module in Python is a convenient way to group keys with similar values. It automatically initializes a new list (or any other default value) for a non-existent key. Here's an example:

from collections import defaultdict
 
def group_keys_by_value(dictionary):
    result = defaultdict(list)
    for key, value in dictionary.items():
        result[value].append(key)
    return result

In this code:

  • We first import defaultdict from collections.
  • Then, we define a function group_keys_by_value that takes a dictionary as an argument.
  • Inside the function, we create a defaultdict called result where the default value is a list.
  • We loop through each key-value pair in the input dictionary. For each value, we append the corresponding key to the list in result associated with that value.
  • Finally, we return the result dictionary.

Using a Regular Dictionary#

We can also achieve the same result using a regular dictionary. Here's how:

def group_keys_by_value_regular(dictionary):
    result = {}
    for key, value in dictionary.items():
        if value not in result:
            result[value] = []
        result[value].append(key)
    return result

In this approach:

  • We define a function group_keys_by_value_regular that takes a dictionary as input.
  • We initialize an empty dictionary result.
  • Then, we loop through each key-value pair. For each value, we check if it's already a key in result. If not, we create a new list for that value. Then, we append the key to the appropriate list in result.
  • Finally, we return the result dictionary.

Best Practices#

  • Use defaultdict when possible: It simplifies the code by handling the initialization of new keys automatically. This reduces the chance of KeyError and makes the code more concise.
  • Error handling: If your input dictionary may have complex or unhashable values (e.g., lists as values), make sure to handle those cases gracefully. For example, you could convert the values to a hashable form (like a tuple if it's a list) before using them as keys in the grouping dictionary.
  • Readability: Choose descriptive variable names. In the examples above, result is a simple name, but if your code is part of a larger project, you might want to use a more meaningful name like grouped_key_dict to make it clear what the variable represents.

Example Usage#

Let's say we have the following dictionary:

my_dict = {
    'apple': 'fruit',
    'banana': 'fruit',
    'carrot': 'vegetable',
    'potato':'vegetable',
    'cherry': 'fruit'
}

Using the group_keys_by_value function (with defaultdict):

grouped = group_keys_by_value(my_dict)
print(grouped)

Output:

defaultdict(<class 'list'>, {'fruit': ['apple', 'banana', 'cherry'],
'vegetable': ['carrot', 'potato']})

Using the group_keys_by_value_regular function:

grouped_regular = group_keys_by_value_regular(my_dict)
print(grouped_regular)

Output:

{'fruit': ['apple', 'banana', 'cherry'],
'vegetable': ['carrot', 'potato']}

References#

This blog post has shown you different ways to group keys with similar values in a Python dictionary. Whether you choose to use defaultdict for simplicity or a regular dictionary for a more basic approach, these techniques can be handy in many data manipulation tasks.