Open In App

Convert List of Tuples to Dictionary Value Lists - Python

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

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

For example, given the list li = [(1, 'gfg'), (1, 'is'), (2, 'best'), (3, 'for'), (4, 'CS')], the goal is to convert it into a dictionary where each key maps to a list of its corresponding values. The resulting dictionary would look like {1: ['gfg', 'is'], 2: ['best'], 3: ['for'], 4: ['CS']} .

Using defaultdict()

defaultdict from the collections module is a efficient way for converting a list of tuples into a dictionary of lists. It automatically initializes keys with a default value like an empty list when they are accessed for the first time, making it ideal for grouping values without additional key checks.

Python
from collections import defaultdict
li = [(1, 'gfg'), (1, 'is'), (2, 'best'), (3, 'for'), (4, 'CS')]

# Create defaultdict with list
res = defaultdict(list)

for i, j in li:
    res[i].append(j)
    
print(dict(res))

Output
{1: ['gfg', 'is'], 2: ['best'], 3: ['for'], 4: ['CS']}

Explanation:

  • for i, j in li: This iterates through each tuple in li, where i is the key and j is the second value .
  • res[i].append(j): This append j to the list associated with key i in res.

Using itertools.groupby

groupby() from the itertools module is a powerful function for grouping items in a list of tuples into a dictionary of lists. It requires the input list to be sorted by the key as it groups adjacent elements with the same key and making it effective for structured data processing.

Python
from itertools import groupby

li = [(1, 'gfg'), (1, 'is'), (2, 'best'), (3, 'for'), (4, 'CS')]

# Sort `li` by the first element of each tuple 
li.sort(key=lambda x: x[0])

res = {key: [val[1] for val in group] for key, group in groupby(li, key=lambda x: x[0])}

print(res)

Output
{1: ['gfg', 'is'], 2: ['best'], 3: ['for'], 4: ['CS']}

Explanation:

  • groupby(li, key=lambda x: x[0]):This groups the sorted list li by the first element of each tuple.
  • for key, group in groupby(li, key=lambda x: x[0]):This iterates over the groups returned by groupby and each group consists of tuples with the same key.
  • [val[1] for val in group]:This list comprehension extracts the second element (val[1]) of each tuple, resulting in a list of values corresponding to the key.
  • {key: [val[1] for val in group]}:This constructs a dictionary where each key maps to the list of values extracted from the group.

Using dictionary comprehension

Dictionary comprehension combined with the filter() function convert a list of tuples into a dictionary of lists. It evaluates each tuple for every unique key and providing a straightforward approach but with less efficiency for larger datasets.

Python
li = [(1, 'gfg'), (1, 'is'), (2, 'best'), (3, 'for'), (4, 'CS')]

res = {key: [val[1] for val in filter(lambda x: x[0] == key, li)] for key in set(k for k, _ in li)}
print(res)

Output
{1: ['gfg', 'is'], 2: ['best'], 3: ['for'], 4: ['CS']}

Explanation:

  • set(k for k, _ in li):This extracts unique keys from li, resulting in {1, 2, 3, 4}.
  • filter(lambda x: x[0] == key, li): This filters li to include tuples where the first element matches the current key.
  • [val[1] for val in filter(...)]: This extracts the value from each filtered tuple for the corresponding key.
  • {key: [...] for key in set(k for k, _ in li)}: This creates a dictionary where each key maps to a list of its corresponding values.

Using loops

This method involves manually initializing a dictionary and explicitly checking if a key exists before appending values. While straightforward and easy to understand, it is less efficient than built-in methods due to repeated key existence checks.

Python
li = [(1, 'gfg'), (1, 'is'), (2, 'best'), (3, 'for'), (4, 'CS')]

res = {}  # Initializes an empty dictionary
for i, j in li:
    if i not in res:
    
        res[i] = [] #Initializes an empty list
    res[i].append(j)

print(res)

Output
{1: ['gfg', 'is'], 2: ['best'], 3: ['for'], 4: ['CS']}

Explanation:

  • for i, j in li: This iterates over each tuple (i, j) in the list li, where i is the key and j is the value.
  • if i not in res: This checks if the key i exists in the dictionary. If not, it initializes an empty list for that key and ensuring a new list is created for each unique key before appending values.
  • res[i].append(j): This appends the value j to the list corresponding to key i.

Next Article
Practice Tags :

Similar Reads