Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python – Convert List of named tuples to dictionary

  • Last Updated : 28 Nov, 2021

In this article, we will convert a list of the named tuples to dictionaries using python.

By using dict() method we can convert a list of named tuples to the dictionary. Before that, we have to convert it into a dictionary using the _asdict() method. 

First, we have to convert namedtuple to the dictionary in each element by using _asdict() method and then we finally convert to the dictionary by using dict() method

Syntax:

for i in list:
     print(dict(i._asdict()))

where,

the list is a named tuple

Example: Python program to convert namedtuple to the dictionary

Python3




# import named tuple
from collections import namedtuple
  
# create a named tuple named DETAILS with three columns
DETAILS = namedtuple("DETAILS", "Name, Age, Subject")
  
# create 5 students
a = [DETAILS("ojaswi", 21, "python"),
     DETAILS("sireesha", 21, "python"),
     DETAILS("gnanesh", 23, "php"),
     DETAILS("priyank", 21, "java"),
     DETAILS("ojaswi", 22, "big-data")]
  
# convert into dictionary
# using dict method
for i in a:
    print(dict(i._asdict()))

Output:

{‘Name’: ‘ojaswi’, ‘Age’: 21, ‘Subject’: ‘python’}

{‘Name’: ‘sireesha’, ‘Age’: 21, ‘Subject’: ‘python’}

{‘Name’: ‘gnanesh’, ‘Age’: 23, ‘Subject’: ‘php’}

{‘Name’: ‘priyank’, ‘Age’: 21, ‘Subject’: ‘java’}



{‘Name’: ‘ojaswi’, ‘Age’: 22, ‘Subject’: ‘big-data’}

Example: Python program to convert namedtuple to a dictionary

Python3




# import named tuple
from collections import namedtuple
  
# create a nmaed tuple named DETAILS with one column
DETAILS = namedtuple("DETAILS", "Name")
  
# create 5 students
a = [DETAILS("ojaswi"),
     DETAILS("sireesha"),
     DETAILS("gnanesh"),
     DETAILS("priyank"),
     DETAILS("ojaswi")]
  
# convert into dictionary
# using dict method
for i in a:
    print(dict(i._asdict()))

Output:

{‘Name’: ‘ojaswi’}

{‘Name’: ‘sireesha’}

{‘Name’: ‘gnanesh’}

{‘Name’: ‘priyank’}

{‘Name’: ‘ojaswi’}


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!