_asdict Method Of Class Namedtuple From The Collections Modules In Python

Method Name:


Method Signature:




Return Value:

A Python dict instance, with the field names and their values populated from the namedtuple object.


  • The class namedtuple enables Python developers to create tuple types with different names.
  • Named tuples also can have their fields named just like the way a CSV file has its fields named by its header.
  • A dictionary object can be obtained from a named tuple using the _dict() method.
  • The method _dict() returns a dictionary, whose keys are the fields of the named tuple and the values are the values corresponding to them.


# Example Python program that creates a dictionary object

# from a namedtuple

import collections as coll


# Create a type responsetime

responsetime             = coll.namedtuple("responsetime", "host, protocol, millisec");


# The responsetime for example.com

example             = responsetime("example.com", "http", 1325);


# Make a dictionary from the named tuple

exampleDictionary   = example._asdict();


print("Responsetime record as a dictionary:");





Responsetime record as a dictionary:

<class 'dict'>

{'host': 'example.com', 'protocol': 'http', 'millisec': 1325}

Copyright 2022 © pythontic.com