Practical-9
Aim: Program to demonstrate different collection
Python Collection Module
The Python collection module is defined as a container that is used to store collections of data, for example - list, dict,
set, and tuple, etc. It was introduced to improve the functionalities of the built-in collection containers.
Python collection module was first introduced in its 2.4 release.
namedtuple()
The Python namedtuple() function returns a tuple-like object with names for each position in the tuple. It was used to
eliminate the problem of remembering the index of each field of a tuple object in ordinary tuples.
1. pranshu = ('James', 24, 'M')
2. print(pranshu)
3. Output:
4. ('James', 24, 'M')
OrderedDict()
The Python OrderedDict() is similar to a dictionary object where keys maintain the order of insertion. If we try to insert
key again, the previous value will be overwritten for that key.
Example
1. import collections
2. d1=collections.OrderedDict()
3. d1['A']=10
4. d1['C']=12
5. d1['B']=11
6. d1['D']=13
7.
8. for k,v in d1.items():
9. print (k,v)
Output:
A 10
C 12
B 11
D 13
defaultdict()
The Python defaultdict() is defined as a dictionary-like object. It is a subclass of the built-in dict class. It provides all
methods provided by dictionary but takes the first argument as a default data type.
1. from collections import defaultdict
2. number = defaultdict(int)
3. number['one'] = 1
4. number['two'] = 2
5. print(number['three'])
Output:
0
Counter()
The Python Counter is a subclass of dictionary object which helps to count hashable objects.
1. from collections import Counter
2. c = Counter()
3. list = [1,2,3,4,5,7,8,5,9,6,10]
4. Counter(list)
5. Counter({1:5,2:4})
6. list = [1,2,4,7,5,1,6,7,6,9,1]
7. c = Counter(list)
8. print(c[1])
Output: