Linux

Python Collections

Up to this level of Python, you have learned data structure of Python. The Python collections module of Python includes implementations of several data structures that extend those found in other modules. Gradually you will learn the power of Python collections module. Let us discuss its power one by one.

Python Named Tuple

So far, we've seen several data types in Python, int, str, list, tuple, dictionary. But if you want to create your own datatype, Python collection namedtuple give you the way to create the own data type. In C language you might have used struct to create own data type.
When you want create a new data type, You might want to ask some questions. What is the name of new datatype, what are the fields of new data type. Let's discuss the syntax of namedtuple.
collections.namedtuple(typename, field_names[, verbose=False][, rename=False])
  1. typename it defines the name of new datatype.
  2. field_names The field_names can be a sequence of strings like ['x', 'y'] or string in which values are white space or "," separated.
  3. if verbose=False then class definition would not printed, good idea to remain it false
  4. if rename=False then invalid fieldnames are automatically replaced with positional names for example 'def, age, empid' is converted to '_0 , age, empid' becuase def is a keyword
Let us discuss our first example
Python Collections named tuple
Python namedtuple
Click to view code
Now you know how to access namedtuple values.
In Next example you will see, how to add list values into Python namedtuple and how to make dictionary from namedtuple.
Python Collections named tuple dictionary
Dictionary from Python namedtuple
Click to view code
You have seen, by using _make you can add list into a namedtuple and by using _asdict you can create dictionary of named tuple
Consider a situation when you want to replace a value from namedtuple. Like tuple the namedtuple are also imutable. But you can use _replace method and reassinging, to replace value from namedtuple.
Python Collections namedtuple replace method
replace method of namedtuple
Click to view code
I hope you have enjoyed the chapter. Press like, share and comment.




admin