Analyse a stream of events
A tiny version of what real services do with logs and analytics: count what happened, group it by user, and keep only the latest few events.
The standard library module collections adds specialised containers: Counter for counting, defaultdict for grouping, deque for fast work at both ends, namedtuple for records, OrderedDict for order-aware dictionaries and ChainMap for layered lookups.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Use Counter to find the most common letter in "mississippi" and print it with its count.
Group ["apple", "avocado", "banana", "blueberry", "cherry"] by first letter using defaultdict(list) and print it as a normal dict.
Keep only the last 3 numbers of [1, 2, 3, 4, 5, 6] using a deque with maxlen, and print them as a list.
Explain it without notes
What problem do Counter and defaultdict solve compared with a plain dict?
Why choose deque instead of a list for a queue?
When would you use ChainMap?
How does a namedtuple differ from a regular tuple and from a dictionary?
How would you build a small LRU (least recently used) cache with the standard library?
Expected output
actions: [('login', 3), ('search', 3), ('logout', 1)]
per user: {'asha': ['login', 'search', 'logout'], 'ravi': ['login', 'search', 'search'], 'meena': ['login']}
last three events: [('ravi', 'search'), ('meena', 'login'), ('ravi', 'search')]
busiest user: [('asha', 3)]