Welcome

sampleqa.in tutorials, python tutorial,python named tuple

Python tutorial


Python Named Tuple in Collections

    Assign name to each element in the tuple, and access individual element by Name rather positional index. Tuple is a immutable objects i.e once tuple is created elements can not be added or deleted. Same principle applies to Namedtuple also, NamedTuple is a another container class, Mainly used for reading comma,or tab seperated files like CSV files, tabler data from execl file or reading table data from databases.etc.,

namedtuple class located in collections module

Syntax for creating namedtuple object
namedtuple(typename,field_names,*,rename=False,defaults=None,module=None)


typename subclass of tuple named typename
filed_namesField names in typename. format for field names.
  1. fields as one string seperated by space or comma
  2. List with each element is a string
renameby default it is False.
If it is set to True, Any repeated fileds will be removed, Any reserved words will also be removed, and replaced with positional paramters
defaultsDefault values can be assigned to individual fields, using iterable or tuple
NamedTuple Example:
 
       Import namedtuple from collections module
       
       >>>from collections import namedtuple
       
       Creating a Address namedtuple  subclass which has following fileds, Name,Street,Zip,Country.       
       >>> Address = namedtuple('Address',['Name','Street','Zip','Country'])

       
       Assign values to each field
       >>> a=Address('sam','gandhi','436636','INDIA')
       
       Display Address Class with associated fileds.
       >>> a
       Address(Name='sam', Street='gandhi', Zip='436636', Country='INDIA')
      
      Accessing Individual Fields
      >>>a.Name
      sam
      >>>a.Street
      gandhi road
      >>>a.Zip
      436636
      >>>a.Country
      India
 
Create a namedtuple with default values
 >>>Address = namedtuple('Address',['Name','Street','Zip','Country'],defaults=tuple('sam','gandhi road','45544','India'))

This is same as above,  Instantiate with empty arguments
>>>a=Address()

Display Address class with associated fields
>>>a
Address(Name='sam', Street='gandhi road', Zip='45544', Country='India')
 
Create a namedtuple from a Dictionary
  
  
   //Dictionary with same field Names as named tuple
   >>>d={'Name':'sam','Street':'gandhi road','Zip':'45544','Country':'India'} 

  
  Method 1

   >>>Address = namedtuple('Address',['Name','Street','Zip','Country'],defaults=d.values())
  Note:Order of the keys should match with named tuple


  Method 2
      //Instantiating Address class with values of Dictionary. i.e  
      Keys should match field names in named tuple, values will be assigned to each filed
      
  >>>a=Address(**d) 
  Note:Dictionary element keys can be  in any order
  
  //Display Address Instance values
  >>>a
  Address(Name='sam', Street='gandhi road', Zip='45544', Country='India')

 

ADS