Search

02 May, 2018

Exploring COLLECTIONS module from Python


The 'collections' module has some interesting methods that give us an edge over generic inbuilt tools . I want to explore them here today and show how you can use them .

namedtuple


Tuples are represented as (item1, item2, item2, ...) . They support indexing and one of the ways to use them is :


>>> from collections import namedtuple
>>> Car = namedtuple('Car','Price Mileage Colour Class')
>>> xyz = Car(Price = 100000, Mileage = 30, Colour = 'Cyan', Class = 'Y')
>>> print xyz
Car(Price=100000, Mileage=30, Colour='Cyan', Class='Y')
>>> print xyz.Class
Y

They turn tuples into convenient containers for simple tasks. With namedtuples, you don’t have to use integer indices for accessing members of a tuple.



defaultdict


Idea is to have a predefined type of value for each key of the dictionary.

Example:


>>> d = defaultdict(list)
>>> d
defaultdict(<type 'list'>, {})
>>> d['names'].append('adam')
>>> d['choices'].append('painting')
>>> d['choices'].append('music')
>>> d
defaultdict(<type 'list'>, {'names': ['adam'], 'choices': ['painting', 'music']})
>>> for i in d.items():
 print i

 
('names', ['adam'])
('choices', ['painting', 'music'])
>>> d.items()
[('names', ['adam']), ('choices', ['painting', 'music'])]



counter


This is probably the favorite available function in collections module. 


>>> from collections import Counter
>>> 
   Counter(['a', 'b', 'a', 'c', 'a', 'd', 'b' ])
Counter({'a': 3, 'b': 2, 'c': 1, 'd': 1})




OrderedDict

Dictionaries in python , ordinarily don't remember the order of items . If you print it, the order may be anything . Not necessarily in the same order in which you created it. If , you want keep the order fixed, so that , it remembers the order of the keys that were inserted first, you can use a special dictionary called "OrderedDict"


>>> from collections import OrderedDict
>>> od = OrderedDict()
>>> od['a']=1
>>> od['b']=10
>>> od['x'] = 20
>>> od['y'] = 30
>>> od['m'] = 40
>>> od['n'] = 50
>>> od
OrderedDict([('a', 1), ('b', 10), ('x', 20), ('y', 30), ('m', 40), ('n', 50)])
>>> od.values()
[1, 10, 20, 30, 40, 50]
>>> od.keys()
['a', 'b', 'x', 'y', 'm', 'n']
>>> od['x']=21
>>> od
OrderedDict([('a', 1), ('b', 10), ('x', 21), ('y', 30), ('m', 40), ('n', 50)])

In case you are wondering, if you can insert a key-value pair at a position of your choice, then I am afraid, there is no built-in method for this . You can add a method yourself by creating another class that inherits from OrderedDict . Refer this question from StackOverflow.


No comments:

Post a Comment