Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

2 Answers
Maheshwari Thakur

In the collections there are some container datatypes, which are alternatives to python’s general purpose built-in containers like dict, list, set etc.

Some of the containers are −

Sr.No.Container & Description
1namedtuple()
Used to create tuple subclass with the name field
2deque
Queue using list type data
3Counter
Subclass of dict to count the hash-table objects
4ChainMap
Used to create single view of multiple mappings
5OrderedDict
Subclass of dict, where data are added in ordered manner
6UserList
Wrapper for list to easier access.

To use this module, we should import it using −

import collections

Deque Object

The Deque is basically a generalization of stack and queue structure, where it is initialized from left to right. It uses the list object to create a deque.

Some Deque related methods are −

Sr.No.Methods & Description
1append(x)
Add element x at the right side of the deque
2appendleft(x)
Add element x at the left side of the deque
3clear()
Clear the deque
4count(x)
Count number of occurrences of x in the deque
5index(x[, start[,stop]])
Return the position of x. If the start and stop are defined, it will find in that range
6insert(i, x)
Insert x into the deque at position i
7pop()
Remove and return element from the right side
8popleft()
Remove and return element from the left side
9reverse()
Reverse the contents of the deque
10rotate(n = 1)
Rotate deque n times to the right

Example Code

 Live Demo

import collections as col
my_deque = col.deque('124dfre')
print(my_deque)
print("Popped Item: " + str(my_deque.pop()))
print("Popped Item From Left: " + str(my_deque.popleft()))
print(my_deque)

Output

deque(['1', '2', '4', 'd', 'f', 'r', 'e'])
Popped Item: e
Popped Item From Left: 1
deque(['2', '4', 'd', 'f', 'r'])

Counter Object

The counter is a subclass of a dict type object. It can be used to count the key values. The counters allow only integer value.

Some Counters related methods are −

Sr.No.Methods & Description
1elements()
Return the elements, that much times the counter value holds.
2most_common([n])
This method returns a list of most commonly used n elements from the counter. If n is not specified, it will return all.
3subtract(iterable or mapping)
Subtract the counter value from two counter object, where keys are matched.
4update(iterable or mapping)
It adds the values without replacing the values, where keys are matched.

Example Code

 Live Demo

import collections as col
text_list = ['ABC','PQR','ABC','ABC','PQR','Mno','xyz','PQR','ABC','xyz']
my_counter = col.Counter()
for element in text_list:
my_counter[element] += 1
print(my_counter)
print(my_counter.most_common(2))

Output

Counter({'ABC': 4, 'PQR': 3, 'xyz': 2, 'Mno': 1})
[('ABC', 4), ('PQR', 3)]

ChainMap Object

The ChainMap is used to encapsulates the dictionaries into single unit.

Some ChainMap members are −

Sr.No.Methods & Description
1maps
It is used to return keys with its corresponding values.
2new_child(m = None)
This method is used to insert a new dictionary at the first position of the chain.

Example Code

import collections as col
con_code1 = {'India' : 'IN', 'China' : 'CN'}
con_code2 = {'France' : 'FR', 'United Kingdom' : 'GB'}
code = {'Japan' : 'JP'}
chain = col.ChainMap(con_code1, con_code2)
print("Initial Chain: " + str(chain.maps))
chain = chain.new_child(code) #Insert New Child
print("Final Chain: " + str(chain.maps))

Output

Initial Chain: [{'India': 'IN', 'China': 'CN'}, {'France': 'FR', 'United Kingdom': 'GB'}]
Final Chain: [{'Japan': 'JP'}, {'India': 'IN', 'China': 'CN'}, {'France': 'FR', 'United Kingdom': 'GB'}]

Arushi

Among Python’s built-in types, list, tuple and dict are known as container data types. The collection module provides some more specialized alternatives to built-in types by improvising them.

Counter

The Counter class is subclassed from built-in dict class. Object of Count class is a key-value pair. Key is an element in sequence or dicrionary and value is count of its occurences.

Empty Counter object is created as follows −

>>> c=Counter()
>>> c
Counter()

Counter object can also be created from a sequence such as list or string.

>>> c = Counter('Hello World')
>>> c
Counter({'l': 3, 'o': 2, 'H': 1, 'e': 1, ' ': 1, 'W': 1, 'r': 1, 'd': 1})
>>> c=Counter([5,2,7,2,8,1,7,5,2])
>>> c
Counter({2: 3, 5: 2, 7: 2, 8: 1, 1: 1}

You can also construct Counter object from dictionary which itself should be k-v pair of element and count

>>> c=Counter({'a':3, 'b':2, 'c':1})

The elements() method of Counter object returns an iterator of element and value repeating as many times as value.

['a', 'a', 'a', 'b', 'b', 'c']

namedtuple

The namedtuple class is derived from built-in tuple class. The namedtuple object contains named fields. Elements in the tuple-like object are accessed by field name as well as index as in case of a normal tuple. The constructor defines the field names

collections.namedtuple(typename, fieldlist)

Following statement defines a new data type called employee with name, department and salary as its fields.

>>> from collections import namedtuple
>>> emp=namedtuple('employee', ['name', 'post', 'dept'])

To create an object of this namedtuple

>>> e1=emp('Kiran','Manager', 'Sales')

Value of a certain field can be accessed by its field attribute

>>> e1.dept
'Sales'

Or its index

>>> e1[1]
'Manager'

The nametuple has following methods −

_asdict(): It returns an orderdict object, mapping fields to their values

>>> e1._asdict()
OrderedDict([('name', 'Kiran'), ('post', 'Manager'), ('dept', 'Sales')])

_replace(): Value of specified fields can be changed

>>> e1._replace(dept='HR')
employee(name='Kiran', post='Manager', dept='HR')

_fields: returns a tuple of string corresponding to field names

>>> e1._fields
('name', 'post', 'dept')

OrderedDict object

Ordered dictionaries are similar to built-in dictionary objects. However, OrderDict object remembers the order in which key-value pairs are inserted, whereas buolt-in dict doesn’t. When it is traversed, items are returned as per the order of insertion of keys.

Following methods are also available to the OrderDict in addition to those inherited from built-in dict class −

popitem(): removes a key-value pair in LIFO order.

move_to_end(): moves a k-v pair to the end if ‘last’ parameter is true and to beginning if ‘last’ parameter is false.

DefaultDict

A defaultdict works exactly like a normal dict, but it is initialized with a function (“default factory”) The first argument provides the initial value for the default_factory attribute; it defaults to None and provides the default value for a nonexistent key. As a result defaultdict never raises a KeyError.

Following code shows a defaultdict with defaultfactory set to int() function. We can add elements in the dictionary after initializing the object.

>>> df = defaultdict(int)
>>> df['a'] = 100
>>> df['b'] = 200
>>> df
defaultdict(<class 'int'>, {'a': 100, 'b': 200})

Unlike a normal dictionary trying to fetch value of non-existing key doesn’t throw KeyError but 0.

>>> df['a']
100
>>> df['z']
0

We can also set list() as defaultfactory and use a list of tuples, each tuple containing k-v pair

>>> l1=[('a',100), ('b',200)]
>>> df=defaultdict(list)
>>> for k,v in l1:
df[k].append(v)

>>> df
defaultdict(<class 'list'>, {'a': [100], 'b': [200]})

deque

Queue is a FIFO data structure. Although built-in list can be used as a queue (using pop() to remove front element and append() to add element at rear), ot is not efficient for this type of operation because items towards right will be shifted by one index towards left every time an item is removed.

The collections module in Python’s library provides deque object. supports memory efficient appends and pops from either ends of a list.

from collections import deque
q=deque([10,20,30,40])

A deque object supports following methods −

append(): Add element to the right side.

appendleft(): Add element to the left side.

pop(): Remove and return an element from the right side.

popleft(): Remove and return an element from the left side.

Example

>>> from collections import deque
>>> dq = deque([1,2,3,4])
>>> dg
Traceback (most recent call last):
   File "<pyshell#29>", line 1, in <module>
   dg
NameError: name 'dg' is not defined
>>> dq
deque([1, 2, 3, 4])
>>> dq.append(5)
>>> dq
deque([1, 2, 3, 4, 5])
>>> dq.pop()
5
>>> dq
deque([1, 2, 3, 4])
>>> dq.popleft()
1
>>> dq
deque([2, 3, 4])
>>> dq.appendleft(0)
>>> dq
deque([0, 2, 3, 4])

The collection module also defines UserList, UserDict and UserString classes which can be used as wrappers to built-in counterparts, list, dict and string. However, their utility has been diminished with Python’s later versions allowing built-in containers to be subclassed.

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.