Python’s collections module

Hi guys welcome back, lets cover some more interesting aspects of python. Let us now deal with a module that can certainly be used in our day to day simple programs, it’s some what for intermediated level. In this section i’ll be telling about collections module, in this module we will dealing with OrderedDict and defaultdict as of now.


This module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, dict, list, set, and tuple.

Lets begin with OrderedDict()

I hope you people have sound knowledge of Dictionary in python, if not then i would recommend you to go through Beginner tutorial section. In simple words, “Ordered dictionaries are just like regular dictionaries but they remember the order that items were inserted. When iterating over an ordered dictionary, the items are returned in the order their keys were first added.

Here is an small example to demonstrate the behaviour of OrderedDict()

>>> import collections
>>> d={}
>>> d['google']='Company'
>>> d['lambhorgini']='Car'
>>> d['']='Python Programming’
>>> for k,v in d.items():
...     print k,v
... Python Programming
google Company
lambhorgini Car

Notice the order of the Dict here, as evident it is random, now lets see what does OrderedDict() does

>>> d = collections.OrderedDict()
>>> d['google']='Company'
>>> d['lambhorgini']='Car'
>>> d['']='Python Programming'
>>> for i,j in d.items():
...     print i,j
google Company
lambhorgini Car Python Programming

hmm…i hope you people have got the difference by seeing at the results produced by them.

Common Dict does not track the insertion order, and iterating over it produces the values in an arbitrary order. In an OrderedDict, by contrast, the order the items are inserted is remembered and used when creating an iterator.

Now lets move over to defaultdict()

using defaultdict() it is possible to group a sequence of key-value pairs into a dictionary of list.

Consider the below example which gives you the exact picture

>>> listOfSets = [(‘ABC',1),('DEF',2),('ABC',3),('LMN',4),('PTR',5),('OPQ',6)]
>>> from collections import defaultdict
>>> defaultD = defaultdict(list)
>>> for k,v in listOfSets:
...     defaultD[k].append(v)
>>> defaultD.items()
[('OPQ', [6]), ('ABC', [1, 3]), ('LMN', [4]), ('DEF', [2]), ('PTR', [5])]

When each key is encountered for the first time, it is not already in the mapping; so an entry is automatically, when keys are encountered again, the look-up proceeds normally (returning the list for that key) and the list.append() operation adds another value to the list. This technique is simpler and faster.

Look at the below example which will help you getting the things faster, we all have come across one common programming question that is to keep/return the count of occurrences of a letter given the string. Let solve the problem here with Infamous Python.

>>> PytLovers = "Hey Guys, hope you are enjoying our tutorial"
>>> defaultDpython = defaultdict(int)
>>> for k in PytLovers:
...     defaultDpython[k]+=1
>>> defaultDpython.items()
[('a', 2), (' ', 7), ('e', 4), ('g', 1), ('G', 1), ('i', 2), ('H', 1), ('j', 1), (',', 1), ('o', 5), ('n', 2), ('p', 1), ('s', 1), ('r', 3), ('u', 4), ('t', 2), ('h', 1), ('y', 4), ('l', 1)]

So i hope you had fun time learning this interesting concept of Mr. Python.

To learn more about the collections module you can visit the official site of Python, here is the link for the same

So in case of any queries or question do reach us, We will help you in best possible way to keep the things going in you favour, Thank you.