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

[‘ChainMap’, ‘Counter’, ‘OrderedDict’, ‘UserDict’, ‘UserList’, ‘UserString’, ‘_Link’, ‘_OrderedDictItemsView’, ‘_OrderedDictKeysView’, ‘_OrderedDictValuesView’, ‘__all__’, ‘__builtins__’, ‘__cached__’, ‘__doc__’, ‘__file__’, ‘__getattr__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘__path__’, ‘__spec__’, ‘_chain’, ‘_collections_abc’, ‘_count_elements’, ‘_eq’, ‘_heapq’, ‘_iskeyword’, ‘_itemgetter’, ‘_proxy’, ‘_recursive_repr’, ‘_repeat’, ‘_starmap’, ‘_sys’, ‘_tuplegetter’, ‘abc’, ‘defaultdict’, ‘deque’, ‘namedtuple’]

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

Counter({4: 3, ‘b’: 2, ‘a’: 1, 10: 1, ‘A’: 1})

We can also pass strings to the counter class.

Example of using Counter in Python

import collections

c = collections.Counter("PythonGeeks")
print(c)

Output

Counter({‘e’: 2, ‘P’: 1, ‘y’: 1, ‘t’: 1, ‘h’: 1, ‘o’: 1, ‘n’: 1, ‘G’: 1, ‘k’: 1, ‘s’: 1})

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

2
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

0

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({‘A’: 2, ‘b’: 1, ‘c’: 1})
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

Counter({‘A’: 2, ‘b’: 1, ‘c’: 1})
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

Element : CountA : 2

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

[(‘e’, 3), (‘o’, 2), (‘k’, 2)]

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

Counter({‘a’: 2, ‘c’: 2, ‘d’: 2, ‘b’: 1, ‘e’: 1})

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

defaultdict(<function <lambda> at 0x10898d280>, {2: 3})PythonGeeks

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

PythonGeeks

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

defaultdict(<class ‘list’>, {1: [2]})

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

OrderedDict([(‘Name’, ‘John’), (‘Age’, 18), (‘Gender’, ‘Male’)])

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’)])OrderedDict([(‘Age’, 18), (‘Gender’, ‘Male’), (‘Name’, ‘John’)])

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), (‘Gender’, ‘Male’)])(‘Gender’, ‘Male’)

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

Student(Name=’Tej’, ID=24)

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 16Nithya 16

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

Student(Name=’Ross’, ID=25){‘Name’: ‘Ross’, ‘ID’: 25}

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

Student(Name=’Sam’, ID=1)
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

(‘Name’, ‘ID’)
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

Student(Name=’Chandler’, ID=20)Student(Name=’Chandler’, ID=4)

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

Student(Name=’Sam’, ID=1)

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

Counter({1: 3, 2: 3, 3: 3})

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

3

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

OrderedDict()

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

Car(Make=’Toyota’, Model=’Camry’)

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

Car(Make=’Ford’, Model=’Figo’)

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.

Did you like this article? If Yes, please give PythonGeeks 5 Stars on Google | Facebook


Leave a Reply

Your email address will not be published. Required fields are marked *