Convert Tuples to Dictionary - Python
Last Updated :
21 Jan, 2025
The task is to convert a list of tuples into a dictionary where each tuple contains two element . The first element of each tuple becomes the key and the second element becomes the value. If a key appears multiple times its values should be grouped together, typically in a list.
For example, given the list li = [("akash", 10), ("gaurav", 12), ("anand", 14), ("akash", 20)]
, the goal is to convert it into a dictionary where each key maps to a list of its corresponding values, like {'akash': [10, 20], 'gaurav': [12], 'anand': [14]}
.
Using groupby()
We can use groupby()
to convert tuples into a dictionary where the first element of each tuple becomes the key, and the second element becomes the value. However before using groupby()
the list must be sorted by the key, as groupby()
only groups consecutive elements with the same value.
Python
from itertools import groupby
li = [("akash", 10), ("gaurav", 12), ("anand", 14),
("suraj", 20), ("akhil", 25), ("ashish", 30)]
# Sort the list before applying groupby
li.sort(key=lambda x: x[0])
res = {key: [value for key, value in group] for key, group in groupby(li, key=lambda x: x[0])}
print(res)
Output{'akash': [10], 'akhil': [25], 'anand': [14], 'ashish': [30], 'gaurav': [12], 'suraj': [20]}
Explanation:
li.sort()
: This sorts the list li based on the first element of each tuple.groupby(li, key=lambda x: x[0])
: This groups consecutive elements by the first element of each tuple.
Using defaultdict()
defaultdict()
from the collections
module simplifies this process of conversion by automatically initializing default values for missing keys. This is especially useful for grouping values under a key without needing manual checks for key existence.
Python
from collections import defaultdict
li = [("akash", 10), ("gaurav", 12), ("anand", 14),
("suraj", 20), ("akhil", 25), ("ashish", 30)]
d = defaultdict(list)
for a, b in li:
d[a].append(b)
print(dict(d))
Output{'akash': [10], 'gaurav': [12], 'anand': [14], 'suraj': [20], 'akhil': [25], 'ashish': [30]}
Explanation:
- defaultdict(list):This creates a dictionary where each key automatically has an empty list as its default value.
- for a, b in li: This iterates through the list of tuples li, where a is the key and b is the value.
- d[a].append(b):This appends the value b to the list corresponding to the key a.
- dict(d):This converts the defaultdict to dictionary d .
Using dict.get()
dict.get() method that checks if a key exists in the dictionary. If it doesn't, it returns a default value . The advantage is that it eliminates the need for explicit checks like if a not in dictionery.
Python
li = [("akash", 10), ("gaurav", 12), ("anand", 14),
("suraj", 20), ("akhil", 25), ("ashish", 30)]
d = {}
for a, b in li:
d[a] = d.get(a, []) + [b]
print(d)
Output{'akash': [10], 'gaurav': [12], 'anand': [14], 'suraj': [20], 'akhil': [25], 'ashish': [30]}
Explanation:
- for a, b in li: This loop iterates through the list li, where a is the key and b is the value.
- d.get(a, []): This checks whether the key a exists in the dictionary d. If it does not exist, it returns an empty list as the default value.
- d[a] = d.get(a, []) + [b]: This concatenates the value b to the existing list for the key a and initializes a new list if the key is not already present.
Using loop
This method involves iterating through the list and manually checking if the key already exists in the dictionary. If the key doesn’t exist, it initializes the key with an empty list. This method is efficient, but it requires more lines of code than defaultdict()
.
Python
li = [("akash", 10), ("gaurav", 12), ("anand", 14),
("suraj", 20), ("akhil", 25), ("ashish", 30)]
d = {}
for a, b in li:
if a not in d:
d[a] = []
d[a].append(b)
print(d)
Output{'akash': [10], 'gaurav': [12], 'anand': [14], 'suraj': [20], 'akhil': [25], 'ashish': [30]}
Explanation:
- for a, b in li: This loop iterates through the list li, where a is the key and b is the value.
if a not in d:
This checks whether the key a
is already in the dictionary d
.d[a] = []
: If the key is not present, it initializes an empty list for that key.d[a].append(b)
: It appends the value b
to the list corresponding to the key a
.
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
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 - Convert dictionary items to values Sometimes, while working with Python dictionary, we can have a problem in which we need to convert all the items of dictionary to a separate value dictionary. This problem can occur in applications in which we receive dictionary in which both keys and values need to be mapped as separate values. Let
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 | 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