Thursday 11 November 2021

Python: Working with namedtuple

‘namedtuple’ method is used to create tuple-like objects that have fields accessible by attribute lookup as well as being indexable and iterable.

 

Signature

collections.namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)

 

Example

Employee = namedtuple("Employee", "id age name")

 

named_tuple_1.py

from collections import namedtuple

Employee = namedtuple("Employee", "id age name")

emp1 = Employee(1, 32, 'Krishna')
print(emp1)

 

Output

Employee(id=1, age=32, name='Krishna')

 

You can access the properties of namedtuple using either index or attribute lookup.

 

named_tuple_2.py

 

from collections import namedtuple

Employee = namedtuple("Employee", "id age name")

emp1 = Employee(1, 32, 'Krishna')

print(emp1)
print('\n')

print('id -> ' + str(emp1.id))
print('age -> ' + str(emp1.age))
print('name -> ' + str(emp1.name))

print('\n')
print('id -> ' + str(emp1[0]))
print('age -> ' + str(emp1[1]))
print('name -> ' + str(emp1[2]))

 

Output

Employee(id=1, age=32, name='Krishna')


id -> 1
age -> 32
name -> Krishna


id -> 1
age -> 32
name -> Krishna

 

namedtuple is a subclass of tuple

 

named_tuple_3.py

 

from collections import namedtuple

Employee = namedtuple("Employee", "id age name")

print('issubclass(Employee, tuple) -> ' + str(issubclass(Employee, tuple)))

 

Output

issubclass(Employee, tuple) -> True

Different ways to specify field names to a namedtuple

a. Specifying an iterable of strings like ["field1", "field2", ..., "fieldN"]

b. Specify a string, where each field name separated by whitespace, like "field1 field2 ... fieldN"

c. Specify a string where each field name separated by commas like "field1, field2, ..., fieldN"

 

named_tuple_4.py

from collections import namedtuple

Employee = namedtuple("Employee", "id age name")
emp1 = Employee(1, 32, 'Krishna')
print(emp1)

Employee = namedtuple("Employee", "id,age,name")
emp1 = Employee(1, 32, 'Krishna')
print(emp1)

Employee = namedtuple("Employee", ['id', 'age', 'name'])
emp1 = Employee(1, 32, 'Krishna')
print(emp1)


Output

Employee(id=1, age=32, name='Krishna')
Employee(id=1, age=32, name='Krishna')
Employee(id=1, age=32, name='Krishna')


Field names can’t start with _ character

 

named_tuple_5.py

from collections import namedtuple

Employee = namedtuple("Employee", "id _age name")
emp1 = Employee(1, 32, 'Krishna')
print(emp1)


Output

    Employee = namedtuple("Employee", "id _age name")
  File "/usr/local/Cellar/python@3.9/3.9.5/Frameworks/Python.framework/Versions/3.9/lib/python3.9/collections/__init__.py", line 399, in namedtuple
    raise ValueError('Field names cannot start with an underscore: '
ValueError: Field names cannot start with an underscore: '_age'


Define namedtuple instance using keyword arguments

 

named_tuple_6.py

from collections import namedtuple

Employee = namedtuple("Employee", "id age name")
emp1 = Employee(id = 1, age = 32, name = 'Krishna')
print(emp1)


Output

Employee(id=1, age=32, name='Krishna')


Convert namedtuple instances to dictionaries

‘_asdict()’ method can be used to convert namedtuple instance to a dictionary.

 

named_tuple_7.py

from collections import namedtuple

Employee = namedtuple("Employee", "id age name")
emp1 = Employee(id = 1, age = 32, name = 'Krishna')
print(emp1._asdict())


Output

{'id': 1, 'age': 32, 'name': 'Krishna'}

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment