5 Best Ways to Convert a Python List of Tuples to a Dict of Lists

πŸ’‘ Problem Formulation: The task is to convert a list of tuples into a dictionary of lists. Each tuple contains several elements and each tuple element needs to form a separate list that corresponds to a dictionary key. For example, converting [('apple', 2), ('banana', 3), ('apple', 5)] to {'apple': [2, 5], 'banana': [3]}.

Method 1: Using DefaultDict

This method involves using a DefaultDict from the collections module, which automatically handles missing keys by creating a new list. This is useful for accumulating elements into lists without having to check if the key exists in the dictionary.

Here’s an example:

from collections import defaultdict

def tuples_to_dict_of_lists(tuples_list):
    result = defaultdict(list)
    for key, value in tuples_list:
        result[key].append(value)
    return dict(result)

example = [('apple', 2), ('banana', 3), ('apple', 5)]
print(tuples_to_dict_of_lists(example))

Output:

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

This code snippet creates a defaultdict where each key refers to a list. As it iterates through the list of tuples, it appends the value from each tuple to the list corresponding to its key.

Method 2: Using setdefault

The setdefault method of a standard dictionary can be used to achieve similar results without importing collections. It ensures that a key exists in the dictionary by setting a default if the key is not already present.

Here’s an example:

def tuples_to_dict_of_lists(tuples_list):
    result = {}
    for key, value in tuples_list:
        result.setdefault(key, []).append(value)
    return result

example = [('apple', 2), ('banana', 3), ('apple', 5)]
print(tuples_to_dict_of_lists(example))

Output:

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

This code makes use of the setdefault method which is available by default on all Python dictionaries. It requires no additional imports and cleanly adds values to lists in the dictionary.

Method 3: Using a For Loop and Checking If Key Exists

This method explicitly checks if a key is already in the dictionary. If not, it creates a new list; otherwise, it appends to the existing list.

Here’s an example:

def tuples_to_dict_of_lists(tuples_list):
    result = {}
    for key, value in tuples_list:
        if key in result:
            result[key].append(value)
        else:
            result[key] = [value]
    return result

example = [('apple', 2), ('banana', 3), ('apple', 5)]
print(tuples_to_dict_of_lists(example))

Output:

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

This code manually checks for the existence of a key and uses basic control flow to construct the dictionary of lists. It is straightforward and does not require any special methods or modules.

Method 4: Using GroupBy from itertools

By using the GroupBy function from the itertools module, you can group elements of the list that have the same key and then convert these groupings into a dictionary of lists.

Here’s an example:

from itertools import groupby
from operator import itemgetter

def tuples_to_dict_of_lists(tuples_list):
    sorted_tuples = sorted(tuples_list, key=itemgetter(0))
    grouped_tuples = groupby(sorted_tuples, key=itemgetter(0))
    return {key: [value for _, value in group] for key, group in grouped_tuples}

example = [('apple', 2), ('banana', 3), ('apple', 5)]
print(tuples_to_dict_of_lists(example))

Output:

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

The code sorts the list of tuples by the first element (the key), and then groups them using groupby. Comprehensions are used to transform these groups into the desired dictionary of lists.

Bonus One-Liner Method 5: Comprehension with groupby

A concise one-liner that leverages dictionary comprehension combined with the groupby function from the itertools module to achieve the result.

Here’s an example:

from itertools import groupby
from operator import itemgetter

tuples_list = [('apple', 2), ('banana', 3), ('apple', 5)]
result = {k: [v for _, v in g] for k, g in groupby(sorted(tuples_list), key=itemgetter(0))}

print(result)

Output:

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

This compact code snippet sorts and groups the list by the first element of each tuple, then creates the dictionary of lists all in one step within a dictionary comprehension.

Summary/Discussion

  • Method 1: DefaultDict. Easy to understand. Handles missing keys automatically. Requires importing the defaultdict from collections.
  • Method 2: setdefault. Avoids the need for additional imports. Neatly handles dictionary key initialization. Might be slightly slower than using defaultdict.
  • Method 3: For Loop with Key Check. Straightforward and explicit. Does not rely on any special functions. Can be verbose and is not the most Pythonic approach.
  • Method 4: GroupBy. Optimized for efficiency. Elegant and concise when dealing with sorted data. Requires knowledge of itertools and additional processing like sorting.
  • Bonus Method 5: One-Liner with groupby. Very concise and Pythonic. Requires a good understanding of both dictionary comprehension and itertools.