All About Collections in Python
In this tutorial, we would be exploring different types of containers implemented by the collections module.
Image by Editor
Python possesses a module named collections which has different types of containers. A container is a python object which consists different objects and implements a way to retrieve those objects and iterate over them.
In this tutorial, we would be exploring different types of containers implemented by the collections module.
- Counters
- OrderedDict
- DefaultDict
- ChainMap
- NamedTuple
- DeQue
Counters
Counters are dict subclass which is used to keep the count of the elements present in an iterable in an unordered dictionary where the key represents the element and value represents the count of the element in the iterable
In order to initialize a counter object, we use the counter () function which can be called in the following waysÂ
from collections import Counter
1) Using sequence of items
counter = Counter(['D','C','C','E','E','E','A','A','X']) print(counter)
Output:
Counter({'D': 1, 'C': 2, 'E': 3, 'A': 2, 'X': 1})
2) Using Dictionary
counter = Counter({'X':3,'Y':2,'Z':1}) print(counter)
Output:
Counter({'X': 3, 'Y': 2, 'Z': 1})
3) Using keyword arguments
counter = Counter(X=3,Y=2,Z=1) print(counter)
Output:
Counter({'X': 3, 'Y': 2, 'Z': 1})
OrderedDict
An orderedDict are dict subclass but not like dictionary, they remember the order in which the keys are inserted
from collections import OrderedDict orderdict = OrderedDict() orderdict["x"] = 2 orderdict["y"] = 3 orderdict["z"] = 4 print(orderdict)
Output:
OrderedDict([('x', 2), ('y', 3), ('z', 4)])
1) When inserting new items in an existing ordered dictionary the new item is attached at the end of the dictionary hence maintaining the order of dictionary
orderdict["v"] = 5 print(orderdict)
Output:
OrderedDict([('x', 2), ('y', 3), ('z', 4), ('v', 5)])
2) When deleting an item from an existing ordered dictionary and inserting the same item again then that particular item is inserted at the end of the dictionaryÂ
del orderdict["x"] print(orderdict)
Output:
OrderedDict([('y', 3), ('z', 4), ('v', 5)])
orderdict["x"] = 2 print(orderdict)
Output:
OrderedDict([('y', 3), ('z', 4), ('v', 5), ('x', 2)])
3) When reassigning or updating the value of an existing key – value pair in an OrderedDict object, the position of the key is maintained but the key gets a new value
orderdict.update(z = "four") print(orderdict)
Output:
OrderedDict([('y', 3), ('z', 'four'), ('v', 5), ('x', 2)]
DefaultDict
A DefaultDict is a dict subclass which provides default values for a key which never exists hence never raising a keyError
from collections import defaultdict
1) Using list as a defaultdict
dftdict = defaultdict(list) for i in range(3): Â Â Â Â dftdict[i].append(i) print(dftdict)
Output:
defaultdict(list, {0: [0], 1: [1], 2: [2]})
2) Using int as a defaultdict
intdict = defaultdict(int) X = [1,2,3,4,5,1,1,3,4,5] for i in X: #The default value is 0 so there is no need to enter the key first intdict[i] += 1 print(intdict)
Output:
defaultdict(int, {1: 3, 2: 1, 3: 2, 4: 2, 5: 2})
ChainMap
ChainMap are used to combine more than one dictionaries into a single unit hence returning a list of dictionaries
from collections import ChainMap x1 = {'a': 0, 'b': 1} x2 = {'c':2,'d':3} x3 = {'e':4,'f':5} chainmap = ChainMap(x1,x2,x3) print(chainmap)
Output:
ChainMap({'a': 0, 'b': 1}, {'c': 2, 'd': 3}, {'e': 4, 'f': 5})
1) Accessing Values using key name
print(chainmap['a'])
Output:
0
2) Accessing ValuesÂ
print(chainmap.values())
Output:
ValuesView(ChainMap({'a': 0, 'b': 1}, {'c': 2, 'd': 3}, {'e': 4, 'f': 5}))
3) Accessing Keys
print(chainmap.keys())
Output:
KeysView(ChainMap({'a': 0, 'b': 1}, {'c': 2, 'd': 3}, {'e': 4, 'f': 5}))
4) Inserting new dictionary
A new dictionary is inserted at the beginning of the ChainMap by using the new_child() method
chainmap1 = chainmap.new_child({'g':6,'h':7}) print(chainmap1)
Output:Â
ChainMap({'g': 6, 'h': 7}, {'a': 0, 'b': 1}, {'c': 2, 'd': 3}, {'e': 4, 'f': 5})
NamedTuple
A NamedTuple is a tuple object having names for every positionÂ
from collections import namedtuple
1) Declaring the namedtuple
band = namedtuple('Country',['name','capital','famousband'])
2) Inserting values to the namedtuple
val = band("south korea","Seoul","BTS") print(val)
Output:
Country(name='south korea', capital='Seoul', famousband='BTS')
3) Accessing the value using index
print(val[0])
Output:
'south korea'
4) Accessing the value using name
print(val.name)
Output:
'south korea'
Deque
A deque is a list for implementing append and pop operations on both sides of the container
from collections import deque
1) Declaring deque
queue = deque([4,5,6]) print(queue)
Output:
deque([4, 5, 6])
2) Using append to insert element at the right which is the end of deque
queue.append(7) print(queue)
Output:
deque([4, 5, 6, 7])
3) Using append to insert element at the left which is the beginning of deque
queue.appendleft(3) print(queue)
Output:
deque([3, 4, 5, 6, 7])
4) Using pop to delete element from the right which is the end of deque
queue.pop() print(queue)
Output:
deque([3, 4, 5, 6])
5) Using popleft to delete element from the left which is the beginning of deque
queue.popleft() print(queue)
Output:
deque([4, 5, 6])
Priya Sengar (Medium, Github) is a Data Scientist with Old Dominion University. Priya is passionate about solving problems in data and converting them into solutions.