Journey to Master Python (WIP)
ageekymonk
32.1K views
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
12
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')
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
8
from collections import defaultdict
addressbook = defaultdict(lambda: "unknown")
addressbook['jason'] = {'name': 'jason bourne', 'age': 40}
print(addressbook['jason'])
print(addressbook['ironman'])
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
11
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))
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
11
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}')
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Suggested playgrounds