Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How can I convert a Python Named tuple to a dictionary?

How can I convert a Python Named tuple to a dictionary?                                           


1 Answer
Pythonista

Namedtuple class is defined in collections module. It returns a new tuple subclass. The new subclass is used to create tuple-like objects that have fields accessible by attribute lookup as well as being indexable and iterable. The constructor takes type name and field list as arguments. For example, a student namedtuple is declared as follows:

>>> from collections import namedtuple
>>> student=namedtuple("student","name, age, marks")

Object of this namedtuple class is declared as:

>>> s1=student("Raam",21,45)

This class has _asdict() method which returns orderdict() object

>>> d=s1._asdict()
>>> d
OrderedDict([('name', 'Raam'), ('age', 21), ('marks', 45)])

To obtain regular dictionary object use dict() function

>>> dct=dict(d)
>>> dct
{'name': 'Raam', 'age': 21, 'marks': 45}
Good
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.