Python - Group list of tuples to dictionary
Last Updated :
21 Jan, 2025
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.
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.
Similar Reads
Convert Dictionary to List of Tuples - Python Converting a dictionary into a list of tuples involves transforming each key-value pair into a tuple, where the key is the first element and the corresponding value is the second. For example, given a dictionary d = {'a': 1, 'b': 2, 'c': 3}, the expected output after conversion is [('a', 1), ('b', 2
3 min read
Convert List of Dictionary to Tuple list Python Given a list of dictionaries, write a Python code to convert the list of dictionaries into a list of tuples.Examples: Input: [{'a':[1, 2, 3], 'b':[4, 5, 6]}, {'c':[7, 8, 9], 'd':[10, 11, 12]}] Output: [('b', 4, 5, 6), ('a', 1, 2, 3), ('d', 10, 11, 12), ('c', 7, 8, 9)] Below are various methods to co
5 min read
Python | List of tuples to dictionary conversion Interconversions are always required while coding in Python, also because of the expansion of Python as a prime language in the field of Data Science. This article discusses yet another problem that converts to dictionary and assigns keys as 1st element of tuple and rest as it's value. Let's discuss
3 min read
Python | Dictionary to list of tuple conversion Inter conversion between the datatypes is a problem that has many use cases and is usual subproblem in the bigger problem to solve. The conversion of tuple to dictionary has been discussed before. This article discusses a converse case in which one converts the dictionary to list of tuples as the wa
5 min read
Convert List of Named Tuples to Dictionary - Python We are given a list of named tuples we need to convert it into dictionary. For example, given a list li = [d("ojaswi"), d("priyank"), d("sireesha")], the goal is to convert it into a dictionary where each unique key maps to a list of its corresponding values, like {'Name': 'ojaswi'},{'Name': 'priyan
2 min read