Python Collections Module – Python Counter, DefaultDict, OrderedDict, NamedTuple

Free Python course with 25 real-time projects Start Now!!

Over the last few days, we opened ourselves up to three subclasses of the class ‘dict’, and function namedtuple().

In this Python Collections Module tutorial, we will study Python Counter, Python DefaultDict, Python OrderedDict, and Python NamedTuple with their subtypes, syntax and examples.

So, let’s start Python Collection Modules.

Python Collections Module - Introduction

Python Collections Module – Introduction

What is Python Collections Module?

The ‘collections’ module in Python that implements special container datatypes. These provide alternatives to Python’s general-purpose built-in containers.

Like we said, all three of these are subclasses of Python class ‘dict’.

>>> from collections import Counter,defaultdict,OrderedDict,namedtuple
>>> issubclass(Counter,dict) and issubclass(defaultdict,dict) and issubclass(OrderedDict,dict)

Output

True
>>> type(namedtuple)

Output

<class ‘function’>

To use any of its functionality, we must first import it.

>>> import collections
Python Collections Module

Python Collections Module

Lets’ see all the collections of Python

Python Collections Counter

The first thing we discuss in this Python Collection Modeule tutorial, is counter in python collections module. Python counter is a container that keeps count of the number of occurrences of any value in the container. It counts hashable objects.

Let’s take an example.

1. Python Counter – Syntax

To define a Python counter, we use the Counter() factory function. To it, we can pass a container like Python list or a tuple, or even a string or a dictionary. We may also use keyword arguments.

>>> from collections import Counter
>>> c=Counter({'a':3,'b':2,'c':1})
>>> c

Output

Counter({‘a’: 3, ‘b’: 2, ‘c’: 1})
>>> c=Counter('Hello')
>>> c

Output

Counter({‘l’: 2, ‘H’: 1, ‘e’: 1, ‘o’: 1})
>>> c=Counter(a=3,b=2,c=1)
>>> c

Output

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

2. Updating a Python Counter

To declare an empty counter in python, and then populate it, we use the update() method.

>>> c=Counter()
>>> c.update('bfg')
>>> c

Output

Counter({‘b’: 1, ‘f’: 1, ‘g’: 1})

3. Accessing Counts in python

To get a value’s count, we pass it as an index to the counter we defined.

>>> c['f']

Output

1
>>> c['h']

As you can see, it does not raise a KeyError.

What are Python Errors and How to Handle Python Errors?

The elements() method returns a python iterator for the values in the container.

>>> for i in c.elements():
                print(f"{i}: {c[i]}")

Output

b: 1f: 1

g: 1

We can also call the most_common() method to get the n most-common values. These are the ones with the highest frequencies.

>>> c=Counter('hello')
>>> c

Output

Counter({‘l’: 2, ‘h’: 1, ‘e’: 1, ‘o’: 1})
>>> c.most_common(2)

Output

[(‘l’, 2), (‘h’, 1)]

4. Python Counter Arithmetic

We can also perform arithmetic on python counters.

>>> c1=Counter('hello')
>>> c2=Counter('help')
>>> c1+c2

Output

Counter({‘l’: 3, ‘h’: 2, ‘e’: 2, ‘o’: 1, ‘p’: 1})
>>> c1&c2

Output

Counter({‘h’: 1, ‘e’: 1, ‘l’: 1})

Python DefaultDict

Python DefaultDict collection, lets us provide a default value for keys. We define it using the defaultdict() factory function, which takes another function as an argument. This function returns a default value for it.

1. Python DefaultDict – Syntax

To define Python defaultdict, we use the factory function defaultdict().

>>> from collections import defaultdict
>>> d=defaultdict(lambda :35)
>>> d['Ayushi']=95
>>> d['Bree']=89
>>> d['Leo']=90.5
>>> d['Adam']

Output

35

Here, we did not initialize ‘Adam’. So, it took 35, because that’s what our function returns to defaultdict(). We can also check the default value with the __missing__() method.

>>> d.__missing__('Adam')

Output

35

2. Using a Type as a Default Factory

We can tell the interpreter what type of values we’re going to work with. We do this by passing it as an argument to defaultdict().

>>> d=defaultdict(list)
>>> for i,j in [('a',(1,2)),('b',(3,4)),('c',(5,6))]:
                d[i].append(j)
>>> d

Output

defaultdict(<class ‘list’>, {‘a’: [(1, 2)], ‘b’: [(3, 4)], ‘c’: [(5, 6)]})

Python OrderedDict

Python OrderedDict, remembers the order in which the key-value pairs were added. Let’s take python ordereddict example.

>>> from collections import OrderedDict
>>> o=OrderedDict()
>>> o['a']=3
>>> o['c']=1
>>> o['b']=4
>>> o

Output

OrderedDict([(‘a’, 3), (‘c’, 1), (‘b’, 4)])

1. Move_to_end()

We’ll take a look at two methods in python orderedDict. The first we discuss is move_to_end(). It lets us move a key-value pair either to the end, or to the front.

>>> o.move_to_end('c')
>>> o

Output

OrderedDict([(‘a’, 3), (‘b’, 4), (‘c’, 1)])
>>> o.move_to_end('c',last=False)
>>> o

Output

OrderedDict([(‘c’, 1), (‘a’, 3), (‘b’, 4)])

2. Popitem()

This method lets us pop a key-value pair out of the container, and then displays it.

>>> o.popitem()

Output

(‘b’, 4)
>>> o.popitem(last=False)

Output

(‘c’, 1)
>>> o

Output

OrderedDict([(‘a’, 3)])

Python NamedTuple

Finally, in python collections module we discuss Python NamedTuple. This is a container that lets us access elements using names/labels.

>>> from collections import namedtuple
>>> colors=namedtuple('colors','r g b')
>>> red=colors(r=255,g=0,b=0)

1. Accessing Elements

To access these elements, we use the dot Python operator.

>>> red.r

Output

255
>>> red.g
>>> red.b

Or, we could just use indices.

>>> red[0]

Output

255

We can also use the getattr() function.

>>> getattr(red,'r')

Output

255

Python namedtuple is immutable. So, you can’t reassign a value directly.

>>> red.r=3
Traceback (most recent call last):
File "<pyshell#95>", line 1, in <module>
red.r=3

Output

AttributeError: can’t set attribute

2. Converting into Python Dictionary

To convert a namedtuple into Python dictionary, we use the _asdict() method.

>>> red._asdict()

Output

OrderedDict([(‘r’, 255), (‘g’, 0), (‘b’, 0)])

3. Converting an Iterable into a namedtuple

The _make() method lets us create a namedtuple from Python list and the format we specified.

>>> colors._make(['1','2','3'])

Output

colors(r=’1′, g=’2′, b=’3′)

4. Creating a namedtuple from the dictionary

To use a dictionary to make python namedtuple, we use this code:

>>> colors(**{'r':255,'g':0,'b':0})

Output

colors(r=255, g=0, b=0)

5. Checking What Fields Belong to the Tuple

For this, we have the _fields attribute.

>>> red._fields

Output

(‘r’, ‘g’, ‘b’)

6. Changing a Value

Like we said, Python namedtuples are immutable. But to change a value, we can use the _replace() method.

>>> red._replace(g=3)

Output

colors(r=255, g=3, b=0)

So, this was all about Pythons Collections Module Tutorial. Hope you like our explanation.

Python Interview Questions on Collection Modules

  1. What is collection module in Python?
  2. What are collection types in Python?
  3. How do you use a collection counter in Python?
  4. What are collection data types in Python?
  5. Is string a collection in Python?

Conclusion

Now that we’ve discussed all four Python collections module- Counter, defaultdict, OrderedDict, and namedtuple with their syntax, methods, and examples of python collections module.

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google | Facebook

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.