Python collections Examples
Short, runnable programs that show python collections module in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python collections Module lesson.
1The most common words in a review
split() makes a list of words, Counter tallies them, and most_common(3) gives the top three. Words with equal counts keep the order in which they first appeared.
from collections import Counter
review = "great food great service but slow service and great price"
words = review.split()
counts = Counter(words)
print(counts.most_common(3))
print(len(counts), "different words out of", len(words))Expected output[('great', 3), ('service', 2), ('food', 1)]
7 different words out of 10
2What is still missing from an order?
Subtracting counters keeps only positive amounts, which is exactly the shortfall. subtract() is the version that keeps zeros and negatives, so it shows the surplus too.
from collections import Counter
stock = Counter({"apples": 5, "pears": 2})
order = Counter({"apples": 3, "pears": 4, "plums": 6})
missing = order - stock
print(missing)
print(sorted(missing))
stock.subtract(order)
print(stock)Expected outputCounter({'plums': 6, 'pears': 2})
['pears', 'plums']
Counter({'apples': 2, 'pears': -2, 'plums': -6})
3Unique pages per visitor with defaultdict(set)
A set ignores duplicates, so asha visiting /home twice is stored once. Sorting the keys and the sets keeps the output stable.
from collections import defaultdict
visits = [("asha", "/home"), ("ben", "/home"), ("asha", "/cart"),
("asha", "/home"), ("ben", "/pay")]
pages = defaultdict(set)
for user, page in visits:
pages[user].add(page)
for user in sorted(pages):
print(user, sorted(pages[user]))Expected outputasha ['/cart', '/home']
ben ['/home', '/pay']
4A print queue that shares the printer
A job that needs more than two pages prints two, then goes to the back of the line. popleft() and append() are both fast on a deque.
from collections import deque
jobs = deque([("report.pdf", 3), ("photo.png", 1), ("invoice.pdf", 2)])
while jobs:
name, pages = jobs.popleft()
if pages > 2:
print("printing 2 pages of", name)
jobs.append((name, pages - 2))
else:
print("finished", name)Expected outputprinting 2 pages of report.pdf
finished photo.png
finished invoice.pdf
finished report.pdf
5A rolling average of the last 3 readings
deque(maxlen=3) forgets the oldest reading as soon as a fourth arrives, so the average always covers only the latest three.
from collections import deque
window = deque(maxlen=3)
for temp in [20, 22, 21, 25, 30, 28]:
window.append(temp)
print(temp, list(window), round(sum(window) / len(window), 1))Expected output20 [20] 20.0
22 [20, 22] 21.0
21 [20, 22, 21] 21.0
25 [22, 21, 25] 22.7
30 [21, 25, 30] 25.3
28 [25, 30, 28] 27.7
6Employee records with namedtuple
Fields are read by name in max() and in the filter. _replace() builds a promoted copy, and _asdict() shows it as a dict ready for JSON.
from collections import namedtuple
Employee = namedtuple("Employee", ["name", "team", "salary"])
staff = [Employee("Asha", "dev", 70000), Employee("Ben", "ops", 52000),
Employee("Cara", "dev", 64000)]
top = max(staff, key=lambda e: e.salary)
print(top.name, top.salary)
promoted = top._replace(salary=top.salary + 5000)
print(promoted)
print(promoted._asdict())
print([e.name for e in staff if e.team == "dev"])Expected outputAsha 70000
Employee(name='Asha', team='dev', salary=75000)
{'name': 'Asha', 'team': 'dev', 'salary': 75000}
['Asha', 'Cara']
Practise next
Python collections Module exercises → Back to the lesson
Python Set Operations examplesPython Dictionaries examplesPython Dictionary Methods examplesPython Modules and Imports examples