Convert List of Named Tuples to Dictionary - Python
Last Updated :
23 Jan, 2025
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': 'priyank'},{'Name': 'sireesha'}.
Using groupby()
We can use groupby() to convert a list of named tuples into a dictionary, where a specific field becomes the key and the corresponding values are grouped together. However, the list must be sorted by the key before using groupby(), as it only groups consecutive elements with the same key.
Python
from collections import namedtuple
from itertools import groupby
# Create a named tuple named DETAILS with one column
d = namedtuple("d", "Name")
li = [d("sireesha"), d("priyank"), d("ojaswi")]
# Sort `li` by the 'Name' field
li.sort(key=lambda x: x.Name)
grouped = groupby(li, key=lambda x: x.Name)
for key, group in grouped:
for item in group:
print({'Name': item.Name})
Output{'Name': 'ojaswi'}
{'Name': 'priyank'}
{'Name': 'sireesha'}
Explanation:
- Groupby(a, key=lambda x: x.Name):This groups the sorted list li by the Name field.
- for item in group: This prints each grouped item as a dictionary with the key 'Name' and its corresponding value.
Using defaultdict()
We can use defaultdict() from the collections module to efficiently convert a list of named tuples into a dictionary. Unlike the regular dict, defaultdict() automatically initializes default values for missing keys, avoiding explicit checks for key existence.
Python
from collections import namedtuple, defaultdict
# Create a named tuple named `d`
d = namedtuple("d", "Name")
# Create 4 students
li = [d("ojaswi"), d("sireesha"), d("gnanesh"), d("priyank")]
# Creates a defaultdict
a = defaultdict(list)
for i in li:
a[i.Name].append(i.Name)
for name in a:
print({'Name': name})
Output{'Name': 'ojaswi'}
{'Name': 'sireesha'}
{'Name': 'gnanesh'}
{'Name': 'priyank'}
Explanation:
- for i in li Loops through each i in the list li.
- a[i.Name].append(i.Name) adds the name to the list corresponding to that name in the dictionary a.
- for name in a loop iterates over the keys of a and prints each Name as dictionary in the format {'Name': value}.
Using list comprehension
list comprehension efficiently convert a list of named tuples into dictionary.
Python
from collections import namedtuple
# Create a named tuple named `d`
d = namedtuple("d", "Name")
li = [d("ojaswi"), d("sireesha"), d("gnanesh"), d("priyank")]
res = [{'Name': student.Name} for student in li]
for item in res:
print(item)
Output{'Name': 'ojaswi'}
{'Name': 'sireesha'}
{'Name': 'gnanesh'}
{'Name': 'priyank'}
Explanation:
- This transforms each named tuple into a dictionary with
"Name"
as the key. - This loops through
res
and prints each dictionary.
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
Python Convert Dictionary to List of Values Python has different types of built-in data structures to manage your data. A list is a collection of ordered items, whereas a dictionary is a key-value pair data. Both of them are unique in their own way. In this article, the dictionary is converted into a list of values in Python using various con
3 min read