Python Practice › Collections Programs
Python Collections Programs with Solutions
20 programs for the collections module: Counter for counting, defaultdict for grouping, deque for queues and sliding windows, namedtuple for records, OrderedDict for an LRU cache and ChainMap for layered settings.
Before you start
Read the Collections lesson first if the topic is new to you.
All programs
- #1Count words with Counter
Write a Python program to count the words in a sentence with Counter.Easy - #2Most common letters
Write a Python program to find the 3 most common letters in a word.Easy - #3Anagram check with Counter
Write a Python program to check whether two words are anagrams using Counter.Easy - #4Add and subtract counters
Write a Python program that combines two inventories with Counter arithmetic.Easy - #5Group words by first letter
Write a Python program to group words by their first letter with defaultdict.Easy - #6Count with defaultdict(int)
Write a Python program to count characters with defaultdict(int).Easy - #7Unique values per key
Write a Python program that collects the unique cities each customer ordered from.Easy - #8Queue with deque
Write a Python program that uses a deque as a first-in, first-out queue.Easy - #9Stack with deque
Write a Python program that uses a deque as a last-in, first-out stack.Easy - #10Keep the last N items
Write a Python program that keeps only the 3 most recent log lines.Easy - #11Moving average with deque
Write a Python program to compute a moving average over a window of 3 values.Medium - #12Rotate a deque
Write a Python program to rotate a list of players for a round-robin game.Easy - #13Records with namedtuple
Write a Python program to store employee records as named tuples.Easy - #14namedtuple helpers
Write a Python program using_asdict,_replaceand_make.Easy - #15LRU cache with OrderedDict
Write a small least-recently-used cache that holds 2 items.Medium - #16Layered settings with ChainMap
Write a Python program that looks up settings in command-line, environment and default layers.Easy - #17Expand a Counter
Write a Python program to list every item of a Counter as many times as its count.Easy - #18Top three scorers
Write a Python program to total player runs from match records and show the top 3.Easy - #19Invert a dictionary with duplicates
Write a Python program to invert a grade dictionary into grade -> students.Easy - #20Palindrome check with deque
Write a Python program to check palindromes by removing characters from both ends of a deque.Easy