Python Intermediate: How to use the Collections Module in Python part – I

Home /

Table of Contents

Collection Modules in Python

Python’s collection Module provides various types of containers. A Container is an object that stores different objects and allows you to access and iterate over them. Tuple, List, Dictionary, and other built-in containers are available. This article will go over the various containers provided by the collections module.


A counter is a dictionary subclass. It is used to keep track of the elements in an iterable as an unordered dictionary, where the key represents the element in the iterable and the value represents the count of that element in the iterable. It is synonymous with a bag or a multiset of other languages.

The counter() function can be used to initialize the counter object, and it can be called in one of the following ways: With a list of items, Using a dictionary with keys and counts, Using keyword arguments to map string names to counts


from collections import Counter
print(Counter({'ball':3, 'egg':5, 'doll':2}))
print(Counter(ball=3, egg=5, doll=2))


Counter({'egg': 5, 'ball': 3, 'doll': 2})
Counter({'egg': 5, 'ball': 3, 'doll': 2})
Counter({'egg': 5, 'ball': 3, 'doll': 2})


An OrderedDict is a subclass of a dictionary that remembers the order in which keys were first inserted. dict() and OrderedDict() are identical; the only difference is that OrderedDict keeps the keys in the order they were inserted. A regular dict does not keep track of the insertion order, so iterating through it returns values in any order. OrderedDict, on the other hand, remembers the order in which the items are inserted.


from collections import OrderedDict
print("\nThis is a Dict")
just_dict = {}
just_dict['a'] , just_dict['b'] , just_dict['c'] , just_dict['d'] = 11, 22, 33, 34
for key, value in just_dict.items():
   print(key, value)
print("\nThis is an Ordered Dict:")
order_dict = OrderedDict()
order_dict['a'] = 11
order_dict['b'] = 22
order_dict['c'] = 33
order_dict['d'] = 44
for key, value in order_dict.items():
   print(key, value)


This is a Dict
a 11
b 22
c 33
d 34
This is an Ordered Dict:
a 11
b 22
c 33
d 44


In Python, a dictionary is an unordered collection of data values that can be used to store data values similar to a map. The Dictionary, as opposed to other Data Types, holds a key-value pair as an element. The key in the dictionary must be unique and immutable. This means that while a Python List cannot be a key, a Python Tuple can. A dictionary can be created by putting a series of elements within curly braces and separating them with a comma.


from collections import defaultdict
default_dict = defaultdict(int)
List = [11, 22, 33, 44, 22, 44, 11, 22]
for item in List:  
   default_dict[item] += 10


defaultdict(<class 'int'>, {11: 20, 22: 30, 33: 10, 44: 20})


Python has a container called “ChainMap” that encapsulates multiple dictionaries into a single unit. ChainMap is a component of the “collections” module. keys(): This function displays all of the keys from all of the dictionaries in ChainMap. values(): This function displays the values of all dictionaries in ChainMap. maps(): This function is used to display the keys and values of all dictionaries in ChainMap.


from collections import ChainMap
dict1 = {'red': 1, 'blue': 2}
dict2 = {'green': 3, 'black': 4}
dict3 = {'pink': 5, 'cyan': 6}
value = ChainMap(dict1, dict2, dict3)
value = ChainMap(dict1, dict2, dict3)
dict3 = { 'yellow' : 5 }
chain = ChainMap(dict1, dict2)
print ("ChainMap contents are : ")
print (chain)
chain1 = chain.new_child(dict3)
print ("Displaying new ChainMap : ")
print (chain1)


ChainMap({'red': 1, 'blue': 2}, {'green': 3, 'black': 4}, {'pink': 5, 'cyan': 6})
ValuesView(ChainMap({'red': 1, 'blue': 2}, {'green': 3, 'black': 4}, {'pink': 5, 'cyan': 6}))
KeysView(ChainMap({'red': 1, 'blue': 2}, {'green': 3, 'black': 4}, {'pink': 5, 'cyan': 6}))
ChainMap contents are :
ChainMap({'red': 1, 'blue': 2}, {'green': 3, 'black': 4})
Displaying new ChainMap :
ChainMap({'yellow': 5}, {'red': 1, 'blue': 2}, {'green': 3, 'black': 4})

Share The Tutorial With Your Friends

Check Our Ebook for This Online Course

Advanced topics are covered in this ebook with many practical examples.

Other Recommended Article