Python Modules – Types, Syntax and Examples

In this article, we will have a brief glance on types of python modules- Counter, Defaultdict, Ordereddict, Namedtuple.

Here, we will have a quick and basic understanding of what these modules are, what’s their function.

Types of Python Modules

1. Counter Module in Python

A counter tool in python provides support from the tallies.class collections. The general Counter([iterable-or-mapping]).

A counter module works on the mutable objects in a python code. It selects the key elements of the dictionary and hence compares them with the rest of the elements. The value which is always allowed, is integral values inclusive of the negative values.

Python Counter Module Example

c = ('a=5', 'b=3', 'c=1', 'd=-1')
print(c)

Output:

a=5′, ‘b=3’, ‘c=1’, ‘d=-1’

most_common([n])

As the name suggests, it returns a list of the ‘n’ numbers which are the most common elements and hence their counts. If (n) includes in the most common list then it is taken as one in a runtime.

The subtract([iterable-or-mapping])

This removes the unwanted element from the list of arrays. It simply waves a wand of magic to the elements which are used less in the array.

fromkeys(iterable): This method helps the coder extract the values of iterable objects from the domainial mutable lists.
update([iterable-or-mapping])

This literal variably updates the already present key values in a code, as instructed by the coder.

Defaultdict Module in Python

Defaultdict in python is yet a very important module.

It imports the immutable library modules in the main source code, with the help of which it acts as a user interface code, in extracting out bulk data in runtime.

Example of Python Defaultdict Module

Dict = {1: 'Tech', 2: 'Vidvan', 3: 'Site'}  
print("YOURDICTIONARYIS: ")  
print(Dict) 
print(Dict[1]) 

Output:

YOURDICTIONARYIS:
{1: ‘Tech’, 2: ‘Vidvan’, 3: ‘Site’}
Tech
>>>

Defaultdict as class:
It acts as a container to the immutable objects in the source code. It is also a subclass of dictionary-like objects also. The main noticeable feature of defaultdict is that it never raises an exception error, until provided with a syntax error.

Syntax:

default.dic(“enter”)

defaultdict(default_factory)

default_factory: It is a basic function, which returns the factory function from the import module to the main source code in run time.

Inner Working of defaultdict

Defaultdict generally parses the internal elements from the list of immutable arrays collected by the coder in runtime of the code.

Python Defaultdict Example

from collections import defaultdict 
d = defaultdict(lambda: "NotPresent") 
d["optionone"] = 20099
d["optiontwo"] = 20090
print(d["optionone"]) 
print(d["option2"]) 
print(d["option1"])

Output:

20099
NotPresent
NotPresent
>>>NotPresent

__missing__(): This is a sub -function of the library class, which searches for the missing variable as instructed by the coder in the whole program in one go.

Code :

from collections import defaultdict 
oneno = defaultdict(int) 
a = [1, 2, 3, 4, 5, 4, 1, 2]
for techno in a: 
    oneno[techno] += 1   
print(oneno) 

Output:

defaultdict(<class ‘int’>, {1: 2, 2: 4, 3: 1, 4: 2})

Named Tuple in Python

The NamedTuple is yet another interesting class, under the collections module.

As the dictionary type objects, it contains keys that are specifically linked with some elements.

Syntax of Python Named Tuple:

Collections.namedtuple

Conversion Procedures of NamedTuple

It converts the inner parsed objects to its library, and then proceeds the same way as the outer loop only.

classmethod somenamedtuple._make(iterable)

Class method that makes a new instance from an existing sequence or iterable within the runtime for user specific codes.

>>> 
#thisistech1 = [100,99]

#thisistech(x=89, y=89)
print (34)

Output:

34

getattr(): To retrieve a field whose name is saved in a string, use the getattr() function within the runtime:

Syntax of getattr in Python:

getattr(p, 'x')

Subclassing Namedtuples

Namedtuple can be parsed as a subclass in any code which is executed in the runtime. This is also done by checking each element of the namedtuple with the library, and then printing the output.

OrderedDict Module in Python

As the name suggests it displays the variables in the form of an ordered dictionary on python code.

In ordered dict the list elements are mutable, i.e they can be changed whenever the user wants. This makes ordereddict frequently used and a better module than any other previous modules.

Example of OrderedDict Module in Python

OrderedDict() 
onumber['p'] = 1
pnumber['q'] = 2
qnumber['r'] = 3
anumber['s'] = 4
  
for key, value in number_.items(): 
    print(key, value) 

Output:

error

Deletion and Re-Inserting: This deletes after elements that are parsed by the user. This can be alternatively done by the for loop as well.

The deleting of the key elements is however not possible in this case because of its high shallow copying property which is inbuilt. However, an effective change can surely be seen in some codes by doing the changes in the main code.

Code:

range=1,2,3,4,5,6,7
for key, value in range: 
    print(key, value)  
print("After deleting the value is:") 
numbertwo.pop('c') 
for key, value in od.items(): 
    print(key, value)   
print("After re-inserting the value is") 
numberone['def'] = 3
for key, value in od.items(): 
    print(key, value) 

Output:

error

Conclusion

In this article, we’ve had a brief description of the types of modules in Python, their functions and usage.

TechVidvan Team

The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today’s tech industry.