collections and datetime

Counter, defaultdict and date arithmetic.

The collections module solves common tasks more briefly than doing it by hand. Counter counts elements:

from collections import Counter
votes = Counter(["tea", "coffee", "tea"])
print(votes["tea"], votes.most_common(1))   # 2 [('tea', 2)]

In a Counter a missing key gives 0, not a KeyError. The most_common(n) method returns the n most frequent elements with their counts.

defaultdict creates the value for a new key by itself. This is handy for grouping:

from collections import defaultdict
groups = defaultdict(list)
for word in ["apple", "avocado", "banana"]:
    groups[word[0]].append(word)
print(dict(groups))   # {'a': ['apple', 'avocado'], 'b': ['banana']}

Without it you would have to check every time whether the key is already in the dictionary.

The datetime module works with dates and times. date.fromisoformat("2026-03-01") turns a string in the YYYY-MM-DD format into a date, and date.today() returns today's date. The difference between two dates is a timedelta, which has a .days attribute. Adding a few days to a date looks like this: day + timedelta(days=7).

from datetime import date, timedelta
start = date(2026, 1, 30)
print(start + timedelta(days=3))   # 2026-02-02

The module takes care of months of different lengths and leap years itself. Do not try to calculate dates by hand with 30 days in a month. strftime("%d.%m.%Y") formats a date the way you need.

Practice

  1. The most frequent

    What does the program print?

    from collections import Counter
    print(Counter("banana").most_common(1))
    
  2. Why defaultdict

    Why is defaultdict(list) more convenient than an ordinary dictionary for grouping?

    • It creates an empty list for a new key by itself
    • It sorts the keys
    • It forbids repeated values
    • It is faster than any list
  3. Days between dates

    Write a function days_between(a, b): the dates come as strings in the YYYY-MM-DD format, and the function returns the number of days between them, always non-negative.