Open In App

Python – Group list of tuples to dictionary

Last Updated : 21 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The task is to convert a list of tuples into a dictionary, where each tuple consists of two elements. The first element of each tuple becomes the key and the second element becomes the value. If a key appears multiple times, its corresponding values should be grouped together, typically in a list.

For example, given the list li = [(‘a’, 1), (‘b’, 2), (‘c’, 3), (‘a’, 4)], the goal is to convert it into a dictionary where each key maps to a list of its values: {‘a’: [1, 4], ‘b’: [2], ‘c’: [3]}.

Using get()

get() method in Python efficiently groups values in a list of tuples by their first element into a dictionary. It checks if a key exists and returns its value, or a default value if not.

Python
li = [(1, 2), (1, 4), (3, 5), (5, 7)]

# Create an empty dictionary
d= {}

# Iterate and group values by the first element of the tuple
for k, v in li:
    d[k] = d.get(k, []) + [v]

print(d)

Output
{1: [2, 4], 3: [5], 5: [7]}

Explanation:

  • get(k, []) retrieves the value of k from d , or an empty list if k is not found.
  • + [v] combines the existing list with the new value v by creating a new list.

Using defaultdict()

collections.defaultdict() is a specialized dictionary that provides a default value for nonexistent keys, making it especially useful when we expect repeated keys and want to aggregate values. If a key doesn’t exist in defaultdict, it is automatically initialized with the specified default value, such as an empty list.

Python
from collections import defaultdict

# List of tuples
li = [(1, 2), (1, 4), (3, 5), (5, 7)]

d = defaultdict(list)
for k, v in li:
    d[k].append(v)

print(dict(d))

Output
{1: [2, 4], 3: [5], 5: [7]}

Explanation: For each tuple (k, v), the value v is appended to the list corresponding to key k in res and if the key doesn’t exist, it is automatically added with an empty list as the default value.

Using itertools.groupby()

groupby() from itertools is used to group the list by the first element. The list must be sorted first, as groupby() only groups consecutive elements with the same key. After grouping, we create a dictionary where each key maps to a list of values.

Python
from itertools import groupby

li = [(1, 2), (1, 4), (3, 5), (5, 7)]

# Sort the list by the first element
li.sort(key=lambda x: x[0])

d = {k: [v for _, v in group] for k, group in groupby(li, key=lambda x: x[0])}

print(d)

Output
{1: [2, 4], 3: [5], 5: [7]}

Explanation:

  • groupby(li, key=lambda x: x[0]) groups the sorted list li by the first element .
  • [v for _, v in group] part extracts the second element from each tuple in the group.
  • {k: …} creates a dictionary where k is the key and the values are the lists of corresponding second elements.

Using for loop

for loop to create a dictionary from a list of tuples works, but it’s less efficient than other methods. It manually checks and updates the dictionary for each key, which adds extra overhead.

Python
li = [(1, 2), (1, 4), (3, 5), (5, 7)]

# Create an empty dictionary
d = {}

# Iterate and group values by the first element of the tuple
for k, v in li:
    if k not in d:
        d[k] = [v]
    else:
        d[k].append(v)

print(d)

Output
{1: [2, 4], 3: [5], 5: [7]}

Explanation:

  • for k, v in li iterates through each tuple in the list li .
  • res[k] = v adds the key-value pair to the dictionary res and if the key k already exists, it updates the value with the new one.


Next Article
Practice Tags :

Similar Reads