Sai A Sai A
Updated date Aug 29, 2023
In this blog, we will explore different methods to convert a standard dictionary into a dictionary of lists in Python. Learn how to efficiently organize and manipulate data by following practical examples using loops, defaultdict, and dict.setdefault().

Introduction:

Dictionaries are a fundamental data structure in Python, allowing us to store and retrieve data with key-value pairs. Often, we encounter scenarios where we need to group multiple values under a single key. In this blog, we will explore different methods to convert a dictionary into a dictionary of lists in Python. 

Method 1: Using a Loop

The simple approach to converting a dictionary into a dictionary of lists is by using a loop. This method involves iterating through the original dictionary and appending values to corresponding lists in the new dictionary.

def dict_to_dict_of_lists_method1(dictionary):
    dict_of_lists = {}
    for key, value in dictionary.items():
        if key in dict_of_lists:
            dict_of_lists[key].append(value)
        else:
            dict_of_lists[key] = [value]
    return dict_of_lists

# Example dictionary
original_dict = {'a': 1, 'b': 2, 'c': 3, 'a': 4}
dict_of_lists_method1 = dict_to_dict_of_lists_method1(original_dict)
print(dict_of_lists_method1)

Output:

{'a': [4], 'b': [2], 'c': [3]}

Method 2: Using defaultdict

The collections module in Python provides a defaultdict class that simplifies the process of creating a dictionary of lists. This method allows you to skip the step of checking if a key exists in the new dictionary before appending values.

from collections import defaultdict

def dict_to_dict_of_lists_method2(dictionary):
    dict_of_lists = defaultdict(list)
    for key, value in dictionary.items():
        dict_of_lists[key].append(value)
    return dict_of_lists

dict_of_lists_method2 = dict_to_dict_of_lists_method2(original_dict)
print(dict_of_lists_method2)

Output:

{'a': [4], 'b': [2], 'c': [3]}

Method 3: Using dict.setdefault()

The dict.setdefault() method provides another efficient way to achieve our goal. It sets a default value for a key if it doesn't exist, allowing us to append values to the list associated with each key.

def dict_to_dict_of_lists_method3(dictionary):
    dict_of_lists = {}
    for key, value in dictionary.items():
        dict_of_lists.setdefault(key, []).append(value)
    return dict_of_lists

dict_of_lists_method3 = dict_to_dict_of_lists_method3(original_dict)
print(dict_of_lists_method3)

Output:

{'a': [4], 'b': [2], 'c': [3]}

Conclusion:

Converting a dictionary into a dictionary of lists enhances the organization and manipulation of data. We have explored three methods to achieve this transformation: using loops, employing the defaultdict class, and utilizing the dict.setdefault() method.

Comments (0)

There are no comments. Be the first to comment!!!