Python tutorial
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 objectnamedtuple(typename,field_names,*,rename=False,defaults=None,module=None)
typename | subclass of tuple named typename |
filed_names | Field names in typename. format for field names.
|
rename | by 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 |
defaults | Default values can be assigned to individual fields, using iterable or tuple |
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 IndiaCreate 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