Today I learnt about python container like dictionaries called "namedtuples" which is present in module called "collections"
Some of the operations performed on namedtuples are
Conversion Operations supported
Extra Operations
Example Code:
Some of the operations performed on namedtuples are
- Access by index
 - Access by keyname
 - Access by getattr
 
Conversion Operations supported
- _make() - returns namedtuple() from iterable passed as an argument.
 - _asdict() - returns OrderedDict() as constructed from the mapped values of namedtuple()
 - ** - This operator is used to convert a dictionary into the namedtuple().
 
Extra Operations
- _fields gives the information about all the key names declared.
 
Example Code:
""" Below examples discusses about namedtuple from collections module """ import collections #Declaring a namedtuple
employee = collections.namedtuple("Employee", ["Name", "Age", "DOB"])
#Adding Values
emp = employee("Johnny Depp", "35", "02011983")
#initializing iterable
ex_list = ["Abraham", "24", "20091994"]
#initializing dict
ex_dict = {"Name" : "Moti", "Age" : 29, "DOB" : "16091987"}
#Below 3print statements print Same output
print(emp.Name) #Access by key
print(emp[0]) #Access by index
print(getattr(emp, "Name")) #Access via getattr
#using _make() to return namedtuple()
print ("The namedtuple instance using iterable is : ")
print(employee._make(ex_list))
#using _asdict() to return an OrderedDict()
print("The OrderedDict instance using namedtuple is :")
print(emp._asdict())
#using ** operator to return namedtuple from dictionary
print("The namedtuple instance from dict is :")
print(employee(**ex_dict))
#print fields of the named tuple
print(emp._fields)
No comments:
Post a Comment