Python collection module

  • There are 4 basic collection data types
    • List, Tuples, Sets, Dictionary
  • Specialised collection data types
    • Counter, OrderedDict, UserDict, UserList, UserString
    • defaultdict, deque, namedtuple(), Chainmap

namedtuple() –> returns a tuple with a named value for each elements in the tuple

import collections

a = collections.namedtuple('course','name, technology')
s = a('DS','Py')
# s = a._make(['DS','Py']) # Using List

print(s) # course(name='DS', technology='Py')

deque (prod - deck) –> is a optimised list to perform insertion and deletion easily

a = ['a','m','r','i','t']
d = collections.deque(a)
print(d) # deque(['a', 'm', 'r', 'i', 't'])


d.append("ap")
print(d) # deque(['a', 'm', 'r', 'i', 't', 'ap'])

d.appendleft('pp')
print(d) # deque(['pp', 'a', 'm', 'r', 'i', 't', 'ap'])

d.pop()
print(d) # deque(['pp', 'a', 'm', 'r', 'i', 't'])

d.popleft()
print(d) # deque(['a', 'm', 'r', 'i', 't'])

Chainmap –> is a dectionary, returns single view of multiple mappings

d1 = {'a': 1, 'b': 2}  
d2 = {'c': 3, 'd': 4}  
d = collections.ChainMap(d1,d2)
print(d) # ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4})

Counter –> is a dictionary subclass for counting hashable objects

a = ['B','B','A','B','C','A']
coun = collections.Counter(a)
print(coun) # Counter({'B': 3, 'A': 2, 'C': 1})

coun.update(['C','A','A']) 
print(coun) # Counter({'B': 3, 'A': 4, 'C': 2})


c1 = collections.Counter(A=4,  B=3, C=10) 
c2 = collections.Counter(A=10, B=3, C=4)   
c1.subtract(c2) 
print(c1) # Counter({'C': 6, 'B': 0, 'A': -6})


print(list(coun.elements()))
# ['B', 'B', 'B', 'A', 'A', 'A', 'A', 'C', 'C']

print(coun.most_common()) # Display in sorted way
# [('A', 4), ('B', 3), ('C', 2)]

OrderedDict –> is a dictionary subclass remembers the order in which the entries were done

d = collections.OrderedDict()
d[1] = 'a'
d[2] = 'm'
d[3] = 'r'
d[4] = 'i'
d[5] = 't'
print(d) # OrderedDict([(1, 'a'), (2, 'm'), (3, 'r'), (4, 'i'), (5, 't')])
print(d.keys()) # odict_keys([1, 2, 3, 4, 5])

print('Poped: ', d.pop(3))

for key, value in d.items(): 
    print(key, value) 

defaultdict –> defualtdict never raises a KeyError

d = collections.defaultdict(int) 
d["a"] = 1
d["b"] = 2
  
print(d["a"]) 
print(d["c"])  # No KeyError -- returns 0

UserDict, UserList, UserString