Change language

Namedtuple in Python

|

Operations on namedtuple ():

Access Operations

1. Index access: the namedtuple () attribute values ​​are ordered and can be accessed using the index number, as opposed to dictionaries, which are not indexed.

2. Keyword access. Keyword access is also allowed, as in dictionaries.

3. using getattr (): — this is another way to access the value by passing namedtuple and the key value as an argument.

# Python code to demonstrate namedtuple () and
# Access by name, index and getattr ()

 
# import & quot; collections & quot; for namedtuple ()

import collections

 
# namedtuple () declaration

Student = collections.namedtuple ( ’Student’ , [ ’name’ , ’ age’ , ’DOB’ ])

 
# Adding values ​​

S = Student ( ’Nandini’ , ’19’ , ’ 2541997’ )

  
# Index access

print ( "The Student age using index is:" , end = "")

print (S [ 1 ])

 
# Access by name

print ( "The Student name using keyname is:" , end = "")

print (S.name)

 
# Access with getattr ()

print ( " The Student DOB using getattr () is: " , end = "")

print ( getattr (S, ’DOB’ ))

Output:

 The Student age using index is: 19 The Student name using keyname is: Nandini The Student DOB using getattr () is: 2541997 

Conversion operations

1. _make (): — This function is used to return a namedtuple () from a repeatable argument passed as an argument.

2. _asdict (): — This function returns : — This function is used to convert a dictionary to namedtuple ().

# Python code to demonstrate namedtuple () and
# _make (), _asdict () and the & quot; ** & quot; operator

 
# import & quot; collections & quot; for namedtuple ()

import collections

 
# namedtuple () declaration

Student = collections.namedtuple ( ’Student’ , [ ’name’ , ’ age’ , ’DOB’ ])

 
# Adding values ​​

S = Student ( ’Nandini’ , ’19’ , ’ 2541997’ )

  
# repeatable initialization

li = [ ’Manjeet’ , ’19’ , ’ 411997’ ]

 
# dict initialization

di = { ’name’ : " Nikhil " , ’age’ : 19 , ’DOB’ : ’ 1391997’ }

  
# using _make () to return namedtuple ()

print ( "The namedtuple instance using iterable is :" )

print (Student._make (li))

 
# using _asdict () to return OrderedDict ()

print ( "The OrderedDict instance using namedtuple is :" )

print (S._asdict ())

 
# using the ** operator to return namedtuple from the dictionary

print ( " The namedtuple instance from dict is : " )

print (Student ( * * di))

Output:

 The namedtuple instance using iterable is: Student (name = ’Manjeet’, age =’ 19’, DOB = ’411997’) The OrderedDict instance using namedtuple is: OrderedDict ([(’ name’, ’Nandini’), (’ age’, ’19’), (’DOB’,’ 2541997’)]) The namedtuple instance from dict is: Student (name = ’Nikhil’, age = 19, DOB =’ 1391997’) 

Additional operations

1. _fields: — This function is used to return all key names of the declared namespace.

2. _replace (): — This function is used to change the values ​​ associated with the passed key name.

# Python code to demonstrate namedtuple () and
# _fields and _replace ()

 
# import & quot; collections & quot; for namedtuple ()

import collections

 
# namedtuple () declaration

Student = collections.namedtuple ( ’Student’ , [ ’name’ , ’ age’ , ’DOB’ ])

 
# Adding values ​​

S = Student ( ’Nandini’ , ’19’ , ’ 2541997’ )

  
# using _fields to display all namedtuple () key names

print ( "All the fields of students are:" )

print (S._fields)

 
# using _replace () to change the namedtuple attribute values ​​

print ( "The modified namedtuple is:" )

print (S._replace (name = ’Manjeet’ ))

Output:

 All the fields of students are: (’name’,’ age’, ’DOB’ ) The modified namedtuple is: Student (name = ’Manjeet’, age =’ 19’, DOB = ’2541997’) 

This article is courtesy of Manjeet Singh . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically