Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 4.10 — The collections Toolbox
Python · Example 1 of 3

Counter and defaultdict

Replace the sentence with your own and see which word is most common.

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.

01

Use Counter to find the most common letter in "mississippi" and print it with its count.

02

Group ["apple", "avocado", "banana", "blueberry", "cherry"] by first letter using defaultdict(list) and print it as a normal dict.

03

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

01

What problem do Counter and defaultdict solve compared with a plain dict?

02

Why choose deque instead of a list for a queue?

03

When would you use ChainMap?

04

How does a namedtuple differ from a regular tuple and from a dictionary?

05

How would you build a small LRU (least recently used) cache with the standard library?

Counter and defaultdict
Sign in to run this example in your browser.

Expected output

counts: Counter({'to': 3, 'be': 3, 'or': 1, 'not': 1, 'that': 1, 'is': 1, 'the': 1, 'question': 1})
top 2: [('to', 3), ('be', 3)]
'to' appears: 3 | 'zebra' appears: 0
after update: 2
letters: Counter({'a': 3, 'n': 2, 'b': 1})
by length: {3: ['pen', 'bag', 'ink'], 4: ['book', 'desk']}
tally: {'m': 1, 'i': 4, 's': 4, 'p': 2}