Python container types

Python Methods and Functions

There are several container data types in collections that are alternatives to the built-in general purpose python containers like dict, list, set, etc.

Some of the containers &

To use this module, we must import it using &

 import collections 

and object

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

Some Deque related methods:

Sample Code

 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) 


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

Object counter

The counter is a subclass of a dict object. Can be used to count key values. Counters only accept integer values.

Some methods related to counters:

 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)) 


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

ChainMap object

ChainMap is used to encapsulate vocabularies into a single whole.

Some of the ChainMap contributors &

Sample 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:" + st r (chain.maps)) chain = chain.new_child (code) #Insert New Child print ("Final Chain:" + str (chain.maps)) 


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

Get Solution for free from DataCamp guru