The collection module in python provides different types of containers. A container is a object that stores collection of objects. containers can be used to store and organize the data in your programs. The collections module provides some of the containers are tuple, list, dictionary, etc.
In this tutorial we will look into different methods provided collection module.
- Counters
- OrderedDict
- DefaultDict
- ChainMap
- NamedTuple
- DeQue
- UserDict
- UserList
- UserString
Counters
A counter is a sub-class of the dictionary. It is used for counting hashable objects.
from collections import Counter print(Counter(['x','x','y','x','z','x','y', 'z','y','y']))
output:
Counter({'x': 4, 'y': 4, 'z': 2})
OrderdDict
A orderdDict is a sub-class of the dictionary. Where keys maintain the order of insertion.
from collections import OrderedDict c = {} c['p'] = 5 c['q'] = 8 c['r'] = 9 c['s'] = 7 for key, value in c.items(): print(key, value)
output:
p 5 q 8 r 9 s 7
DefaultDict
A DefaultDict is a sub-class of the dictionary. It provides all methods given by dictionary but takes the first argument as a default data type.
from collections import defaultdict name = defaultdict(int) name['varsha'] = 1 name['sahithi'] = 2 print(name['varsha'])
output:
1
ChainMap
A chainmap class is used to groups multiple dictionary together to create a single list. And it can be accessed by the map attribute.
from collections import ChainMap student_details = {'Name': 'sindhu', 'Age': '20'} employee_details = {'Age': '15', 'Roll_no': '1242'} print(list(ChainMap(employee_details, student_details)))
output:
['Name', 'Age', 'Roll_no']
NamedTuple
This function returns a new tuple subclass with named fields. It can be used to create tuple-like objects with named fields for improved readability.
varsha = ('sath', 2, 'k') print(varsha)
output:
('sath', 2, 'k')
DeQue
DeQue is a double-ended queue. It’s useful for efficiently adding and removing elements from both ends of a sequence.
from collections import deque list = ["a","b","c"] k = deque(list) print(k)
output:
deque(['a', 'b', 'c'])
UserDict
These are wrapper classes that act as proxies for dictionary. A real dictionary used to store the contents of the UserDict class.
UserList
These are wrapper classes that act as proxies for list. A real list is used to store the contents of the User class.
UserString
These are wrapper classes that act as proxies for string. A real str object is used to store the contents of the UserString class.