Python Container Datatypes


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'}]

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements