Journey to Master Python (WIP)

ageekymonk
2,744 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Collections module

Better way to count elements

Collections module provide a Counter class which can used to count elements in a list. It also provides utility functions like most_common for getting most common elements in the list.

counter class
1
2
3
4
5
6
7
8
9
10
11
import collections
c = collections.Counter([1, 2, 3, 1, 3, 1, 3, 4])
print(c)
# Accessing individual elements
print(f'4 is repeated {c[4]} times')
# Finding most common elements
print(f'Most common element is {c.most_common(1)[0][0]} repeated {c.most_common(1)[0][1]} times')
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

defaultdict

defaultdict behaves like normal dict with one key difference. It has a factory function that takes no arguments which provides values for non existent key

defaultdict class
1
2
3
4
5
6
7
from collections import defaultdict
addressbook = defaultdict(lambda: "unknown")
addressbook['jason'] = {'name': 'jason bourne', 'age': 40}
print(addressbook['jason'])
print(addressbook['ironman'])
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

One most popular example is one liner tree function. You can create a nested dict without even initialising its parents.

defaultdict class
1
2
3
4
5
6
7
8
9
10
from collections import defaultdict
import json
def tree():
return defaultdict(tree)
addressbook = tree()
addressbook['jason']['name'] = 'Jason Bourne'
addressbook['jason']['phone']['mobile'] = '11111111'
print(json.dumps(addressbook))
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

namedtuple

namedtuple is a factory function to create tuple like object but can access its elements with attribute name.

namedtuple
1
2
3
4
5
6
7
8
9
10
from collections import namedtuple
Contact = namedtuple('Contact', 'name, age, address')
jason = Contact(name='Jason Bourne', age='40', address='unknown')
print(jason)
print(f'Name: {jason.name} \nage: {jason[1]}')
name, age, address = jason
print(f'Name: {name} \nage: {age}')
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content