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



Namedtuple class is defined in the 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")

The 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