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

1. Collections in Python

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

2. Introduction to 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)

True

>>> type(namedtuple)

<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

3. 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.

a. 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

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

>>> c=Counter('Hello')
>>> c

Counter({‘l’: 2, ‘H’: 1, ‘e’: 1, ‘o’: 1})

>>> c=Counter(a=3,b=2,c=1)
>>> c

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

b. 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

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

c. Accessing Counts in python

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

>>> c['f']

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]}")

b: 1

f: 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

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

>>> c.most_common(2)
[(‘l’, 2), (‘h’, 1)]

d. Python Counter Arithmetic

We can also perform arithmetic on python counters.

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

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

>>> c1&c2

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

4. 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.

a. 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']

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')

35

b. 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

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

Follow this link to know more about Python defaultdict 

5. Python OrderedDict

Python OderDict, 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

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

a. 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

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

>>> o.move_to_end('c',last=False)
>>> o

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

b. Popitem()

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

>>> o.popitem()

(‘b’, 4)

>>> o.popitem(last=False)

(‘c’, 1)

>>> o

OrderedDict([(‘a’, 3)])
Follow this link to know more about Python OrderedDict

Python Interview Questions

6. 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)

a. Accessing Elements

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

>>> red.r

255

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

Or, we could just use indices.

>>> red[0]

255
We can also use the getattr() function.

>>> getattr(red,'r')

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

AttributeError: can’t set attribute

b. Converting into Python Dictionary

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

>>> red._asdict()

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

c. 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'])

colors(r=’1′, g=’2′, b=’3′)
Follow this link to know more about Python Iterables.

d. 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})

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

e. Checking What Fields Belong to the Tuple

For this, we have the _fields attribute.

>>> red._fields

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

f. 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)

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

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

7. 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. We can move on to other things. Hope you had fun, If you had any query, write us in a comment box we surely get back to you.
See Also- Python Operator Overloading & Python Variable Scope
For reference

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.