main

2021/06/13

Python Collections library

Ref: https://www.geeksforgeeks.org/python-collections-module/

 1) Counters

It presents a stat of data

from collections import Counter

Counter({"A":5,"B":2})

array = [''cook","book","took","sook","book","book","aook"]

Counter(array)


2) OrderedDict

It remembers the order when key enters into the dict.

print("\nThis is an Ordered Dict:\n"
od = OrderedDict() 
od['a'] = 5
od['b'] = 2
od['c'] = 3
od['d'] = 4
    
for key, value in od.items(): 
    print(key, value)


3) DefaultDict

DefaultDict is also a sub-class to dictionary. It is used to provide some default values for the key that does not exist and never raises a KeyError.


4) ChainMap

ChainMap encapsulates many dictionaries into a single unit and returns a list of dictionaries.

from collections import ChainMap 
     
     
d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'd': 4}
d3 = {'e': 5, 'f': 6}
  
# Defining the chainmap 
c = ChainMap(d1, d2, d3) 
     
print(c)

5)  NamedTuple

NamedTuple returns a tuple object with names for each position which the ordinary tuples lack. For example, consider a tuple names student where the first element represents fname, second represents lname and the third element represents the DOB. Suppose for calling fname instead of remembering the index position you can actually call the element by using the fname argument, then it will be really easy for accessing tuples element. This functionality is provided by the NamedTuple.

from collections import namedtuple
# Declaring namedtuple() 
Student = namedtuple('Student',['name','age','DOB']) 
    
# Adding values 
S = Student('Nandini','19','2541997'
    
# Access using index 
print ("The Student age using index is : ",end ="") 
print (S[1]) 
    
# Access using name  
print ("The Student name using keyname is : ",end ="") 
print (S.name)


6. Deque (pronounced deck)

Deque (Doubly Ended Queue) is the optimized list for quicker append and pop operations from both sides of the container. It provides O(1) time complexity for append and pop operations as compared to list with O(n) time complexity.

from collections import deque 
    
# initializing deque 
de = deque([1,2,3]) 
    
# using append() to insert element at right end  
# inserts 4 at the end of deque 
de.append(4
    
# printing modified deque 
print ("The deque after appending at right is : "
print (de) 
    
# using appendleft() to insert element at right end  
# inserts 6 at the beginning of deque 
de.appendleft(6
    
# printing modified deque 
print ("The deque after appending at left is : "

print (de)


7 UserDict

UserDict is a dictionary-like container that acts as a wrapper around the dictionary objects. This container is used when someone wants to create their own dictionary with some modified or new functionality. 

# Creating a Dictionary where 
# deletion is not allowed 
class MyDict(UserDict): 
        
    # Function to stop deleltion 
    # from dictionary 
    def __del__(self): 
        raise RuntimeError("Deletion not allowed"
            
    # Function to stop pop from  
    # dictionary 
    def pop(self, s = None): 
        raise RuntimeError("Deletion not allowed"
            
    # Function to stop popitem  
    # from Dictionary 
    def popitem(self, s = None): 
        raise RuntimeError("Deletion not allowed"
        
# Driver's code 
d = MyDict({'a':1
    'b': 2
    'c': 3})
    
d.pop(1)

8: UserList

9: UserString

No comments:

Post a Comment

How to Supercharge Your Python Classes with Class Methods

  How to Supercharge Your Python Classes with Class Methods | by Siavash Yasini | May, 2024 | Towards Data Science As we just mentioned, a c...