Python Collections Module – Counter, Defaultdict, Ordereddict, Namedtuple
FREE Online Courses: Transform Your Career – Enroll for Free!
In Python, dictionaries and tuples play a major role in creating efficient programs. In this article, we will learn about the Counter, Defaultdict, Orderdict, and Namedtuple classes present in the Python Collections module.
Python Collections Module
Collections is a Python built-in module. We can simply import the module to use its objects. To import a module, we can use the import keyword.
Example of importing a module
import collections print(dir(collections))
Output
In the code example, we imported the collections module and used the dir() function to print all objects of the module. We can see that Counter, defaultdict, OrderedDict, and namedtuple are the objects of the collections module. let us see each of then now:
1. Counter in Python
It is used to count hashable objects. It counts the number of times each element occurs in the passed iterable and stores the elements as dictionary keys and their count as dictionary values.
Syntax
collections.Counter([iterable-or-mapping])
Example of using Counter in Python
import collections c = collections.Counter(["a", 4, 10, 4, 4, "b", "A", "b"]) print(c)
Output
We can also pass strings to the counter class.
Example of using Counter in Python
import collections c = collections.Counter("PythonGeeks") print(c)
Output
Getting the Count of an Element using Counter
After creating the counter object of an iterable or string, we can get the count of a specific element by passing the element as an index of the counter.
Example of Counter in Python
import collections c = collections.Counter("PythonGeeks") print(c["e"]) print(c["P"])
Output
1
If the element we passed is not found in the counter, then it returns 0 instead of raising a KeyError.
Example of Counter in Python
import collections c = collections.Counter("PythonGeeks") print(c["A"])
Output
More Methods of the Counter Class
a. update([iterable-or-mapping])
The method takes an iterable. It counts the number of times each element occurs in that iterable and adds the count to the existing counter object. If the element doesn’t exist in the existing counter object, then it adds a new key-value pair to the counter object.
Example of using update() in Python
import collections c = collections.Counter("AAbc") print(c) c.update("bbc") print(c)
Output
Counter({‘b’: 3, ‘A’: 2, ‘c’: 2})
This method also allows us to populate an existing empty counter object.
Example of using update() in Python
import collections c = collections.Counter() c.update("AbcA") print(c)
Output
b. elements()
This method returns an iterator over all elements in the counter object.
Example of using elements() in Python
import collections c = collections.Counter("AAbc") print("Element : Count") for element in c.elements(): print(f"{element} : {c[element]}")
Output
A : 2
b : 1
c : 1
c. most_common([n])
The method takes an integer n and returns a list containing the n most common elements in the counter object. The list is sorted from most common to least common.
Example of using most_common() in Python
import collections c = collections.Counter("bookkeeper") print(c.most_common(3))
Output
Counter Arithmetic Operations
We can use arithmetic operators on counter objects. For example, the plus operator ‘+’ merges two counter objects.
Example of arithmetic operation on Counters in Python
import collections c1 = collections.Counter("aabc") c2 = collections.Counter("cdde") c3 = c1 + c2 print(c3)
Output
2. defaultdict in Python
The class is used to assign a default value to the keys of a dictionary.
Syntax
collections.defaultdict(default_factory=None, /[, ...])
Example of defaultdict in Python
import collections d = collections.defaultdict(lambda : "PythonGeeks") d[2] = 3 print(d) print(d[1])
Output
In the above code example, since there is no 1 key, it returned the default value without raising a KeyError.
a. __missing__(key) of defaultdict
We can also get the default value of missing keys by using the magic method __missing__().
Example of using __missing__() in Python
import collections d = collections.defaultdict(lambda : "PythonGeeks") print(d.__missing__(1))
Output
Passing Data Types to defaultdict in Python
We can also pass data types to the defaultdict. For example, passing list creates a default empty list for all keys.
Example of using defaultdict in Python
import collections d = collections.defaultdict(list) d[1].append(2) print(d)
Output
3. OrderedDict in Python
The Python OrderedDict class keeps track of the order in which key-value pairs were added. Let’s look at a python OrderedDict as an example.
Syntax
collections.OrderedDict([items])
Example of OrderedDict in Python
import collections o = collections.OrderedDict() o["Name"] = "John" o["Age"] = 18 o["Gender"] = "Male" print(o)
Output
More Methods of the OrderedDict Class
a. move_to_end(key, last=True)
The method moves the passed key to either the end or the start of the Dictionary.
Example of using move_to_end() in Python
import collections o = collections.OrderedDict() o["Name"] = "John" o["Age"] = 18 o["Gender"] = "Male" print(o) o.move_to_end('Name') # Moving to the end print(o) o.move_to_end('Name', last=False) # Moving to the start print(o)
Output
OrderedDict([(‘Name’, ‘John’), (‘Age’, 18), (‘Gender’, ‘Male’)])
b. popitem(last=True)
The method removes and returns either the last or first item of a dictionary.
Example of using popitem() in Python
import collections o = collections.OrderedDict() o["Name"] = "John" o["Age"] = 18 o["Gender"] = "Male" print(o) print(o.popitem()) print(o) print(o.popitem(last=False)) print(o)
Output
OrderedDict([(‘Name’, ‘John’), (‘Age’, 18)])
(‘Name’, ‘John’)
OrderedDict([(‘Age’, 18)])
4. namedtuple in Python
The namedtuple is used to create a tuple of elements that can be accessed using labels or names.
Syntax
collections.namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)
Example of using namedtuple in Python
import collections n = collections.namedtuple('Student', ['Name', 'ID']) emp = n("Tej", 24) print(emp)
Output
Getting Elements from a namedtuple
To get an element from a namedtuple, we can either use labels or normal indexing. The function getattr() can also be used to do this.
Example of namedtuple in Python
import collections n = collections.namedtuple('Student', ['Name', 'ID']) emp = n("Nithya", 16) print(emp.Name, emp.ID) print(emp[0], emp[1]) print(getattr(emp, 'Name'), getattr(emp, 'ID'))
Output
Nithya 16
More methods of the namedtuple Class
a. _asdict()
This method converts a namedtuple into a dictionary.
Example of using _asdict() in Python
import collections n = collections.namedtuple('Student', ['Name', 'ID']) emp = n("Ross", 25) print(emp) d = emp._asdict() print(d)
Output
b. _make(iterable)
This method converts an iterable into a namedtuple.
Example of using _make() in Python
import collections n = collections.namedtuple('Student', ['Name', 'ID']) emp = n._make(["Sam", 1]) print(emp)
Output
c. _fields
This returns a tuple containing the labels of the namedtuple.
Example of using _fields in Python
import collections n = collections.namedtuple('Student', ['Name', 'ID']) emp = n("Chandler", 20) print(emp._fields)
Output
d. _replace(**kwargs)
This method can be used to modify the values of a namedtuple.
Example of using _replace() in Python
import collections n = collections.namedtuple('Student', ['Name', 'ID']) emp = n("Chandler", 20) print(emp) emp = emp._replace(ID=4) print(emp)
Output
Converting Dictionary to namedtuple
To convert a dictionary to namedtuple, we use the double-star-operator ‘**’.
Example of using double-star-operator in Python
import collections n = collections.namedtuple('Student', ['Name', 'ID']) d = {'Name':'Sam', 'ID':1} emp = n(**d) print(emp)
Output
Python Interview Questions on Python Collections Module – Counter, Defaultdict, Ordereddict, Namedtuple
Q1. Write a program to get a dictionary containing the count of all elements in the list [1, 2, 3, 2, 1, 2, 3, 3, 1].
Ans 1. Complete code is as follows:
from collections import Counter li = [1, 2, 3, 2, 1, 2, 3, 3, 1] c = Counter(li) print(c)
Output
Q2. Write a program to print the number of occurrences of ‘A’ in the list [A, A, B, A, C].
Ans 2. Complete code is as follows:
from collections import Counter li = ['A', 'A', 'B', 'A', 'C'] c = Counter(li) print(c['A'])
Output
Q3. Write a program to create an empty ordereddict in Python.
Ans 3. Complete code is as follows:
from collections import OrderedDict o = OrderedDict() print(o)
Output
Q4. Write a program to create a namedtuple representing a car with labels make and model.
Ans 4. Complete code is as follows:
from collections import namedtuple Car = namedtuple('Car', ['Make', 'Model']) sedan = Car('Toyota', 'Camry') print(sedan)
Output
Q5. Write a program to create a namedtuple from a dictionary.
Ans 5. Complete code is as follows:
from collections import namedtuple Car = namedtuple('Car', ['Make', 'Model']) dictionary = {'Make' : 'Ford', 'Model' : 'Figo'} c = Car(**dictionary) print(c)
Output
Conclusion
In this article, we learned about various classes of Python collections module such as Counter, defaultdict, OrderedDict, and namedtuple. We also learned some of their important methods to work with these classes easier. Furthermore, If you have any queries, please post them in the comments section.