_asdict method of class namedtuple from the collections modules in Python

Method Name:

_asdict

Method Signature:

_asdict()

Parameters:

None

Return Value:

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

Overview:

  • 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:

# 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:");

print(type(exampleDictionary));

print(exampleDictionary);

 

Output:

Responsetime record as a dictionary:

<class 'dict'>

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


Copyright 2024 © pythontic.com