Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python collections.namedtuple



The namedtuple() in Python is a data type from the collections module. It assigns a name to each position in a tuple, allowing elements to be accessed by field names, similar to how we access elements in a tuple by index.

The namedtuple() class returns a new tuple subclass named typename. The new subclass is used to created tuple like objects that have fields accessible by attributes and being indexable and iterable. We can access the elements by typename, field name and by passing index values.

Syntax

Following is the syntax of the Python namedtuple() data type −

class collections.namedtuple(typename, field_names, rename, default)

Parameters

This class accepts following parameters −

  • typename : It returns a new tuple subclass named typename[name of tuple]. The new subclass is used to created tuple like objects that have fields accessible by attributes and being indexable and iterable. We can access the elements by typename, field name and by passing index values.

  • field_names: It can be sequence of the strings such as ['x', 'y'] or can be a single string with fieldname separated by white-space or commas. For example, 'x y' or 'x, y'. The field_name can be any python identifiers except the name starting with an underscore or a digit and cannot be a keywords.

  • rename: If it is true, invalid fieldnames are automatically replaced with positional names. For example, ['xyz', 'class', 'mno', 'pqr'] is converted to ['xyz', '4', 'mno', 'pqr'], eliminated the keyword class keyword.

  • default: It can be None or an iterable of default values. Since fields with a default value must come after any fields without a default, the defaults are applied to the rightmost parameters. For example, if the fieldnames are ['p', 'q', 'r'] and the defaults are (10,20), then p will be a required argument, q will default to 10, and r will default to 20.

Return Value

This class returns a new subclass tuple.

Example

Following is the basic example of the Python namedtuple() data type −

from collections import namedtuple
student1 = namedtuple('student1',['name','rollno', 'marks'])
var = student1(name = 'Sai',rollno=237, marks=89)
print("Name :",var.name)
print("Rollno :",var.rollno)
print("Marks :",var.marks)

Following is the output of the above code −

Name : Sai
Rollno : 237
Marks : 89

Using namedtuple() with _.make()

The _.make() will initialize values of the existing namedtuple to with a iterable. It accepts the iterable as an argument.

Example

Here, we have created a tuple using namedtuple() and named student1 and replaced the elements of it using make() method −

from collections import namedtuple
student1 = namedtuple('student1',['name','rollno', 'marks'])
var = student1('John', 202, 75)
print(var)
tup1 = [12, 45, 89]
print(student1._make(tup1))

Following is the output of the above code −

student1(name='John', rollno=202, marks=75)
student1(name=12, rollno=45, marks=89)

Using namedtuple() with ._asdict()

The tuple which is created using namedtuple() class can be converted into dictionary by _asdict() method.

Example

Here, we have tuple named dic1 and converted to dictionary using _asdict() method −

from collections import namedtuple
dic1 = namedtuple('dic1',['Telangana','TamilNadu', 'Karnataka'])
var = dic1('Hyderabad', 'Chennai', 'Bangalore',)
print(var._asdict())

Following is the output of the above code −

{'Telangana': 'Hyderabad', 'TamilNadu': 'Chennai', 'Karnataka': 'Bangalore'}

Using namedtuple() with ._replace()

The replace() method returns a new instance of the named tuple replacing specified fields with new values.

Example

Following is an example of usage of replace() with namedtuple

from collections import namedtuple
list1 = namedtuple('list1',['x', 'y']) 
var = list1(x=10, y=90)
print(var._replace(x=55))

Following is the output of the above code −

list1(x=55, y=90)

Using namedtuple() with _field

The _field() method is used to concatenate two namedtuples and the tuple of strings listing the field names. Useful for introspection and for creating new named tuple types from existing named tuples.

Example

Here, we have created two tuples and concatenated into a single tuple using _fields and assigned values −

from collections import namedtuple
tup1 = namedtuple('tup1',['x1','y1','z1'])
tup2 = namedtuple('tup2',['x2','y2','z2'])
Newtup = namedtuple('Newtup', tup1._fields + tup2._fields)
res = Newtup(12,14,16,18,20,22)
print(res)

Following is the output of the above code −

Newtup(x1=12, y1=14, z1=16, x2=18, y2=20, z2=22)

Using namedtuple with _field_defaults

The dictionary mapping field names to default values is done using _field_defaults method in namedtuples. If we pass the arguments less than the defined string list then it take default value for the other argument.

Example

Here, we have created a namedtuple, My_tup1 with 2 fieldnames and given a default value -1. We have passed a single value into the My_tup1 but resulted in 2 values because of _field_defaults() method −

from collections import namedtuple
My_tup1 = namedtuple('My_tup1',['val1', 'val2'],defaults=[-1])
res = My_tup1._field_defaults
print("default value :",res)
print(My_tup1(12))

Following is the output of the above code −

default value : {'val2': -1}
My_tup1(val1=12, val2=-1)
python_modules.htm
Advertisements