Python

 

 

In Python, the collections module offers a collection of specialized container datatypes that can be very helpful in various programming scenarios. The most commonly used are NamedTuple, defaultdict, and Counter. These data structures enhance performance and make the code more readable and efficient.

Objective

This tutorial aims to introduce three powerful features of Python’s collections module:

  • NamedTuple: A subclass of the built-in tuple data structure that allows for more readable and self-documenting code.
  • defaultdict: A dictionary subclass that returns a default value when a key is accessed that doesn’t exist.
  • Counter: A subclass of the dictionary that counts the occurrences of elements in an iterable.

Code Example

Below is an example of using NamedTuple, defaultdict, and Counter in Python:


from collections import namedtuple, defaultdict, Counter

# 1. NamedTuple Example
Person = namedtuple('Person', ['name', 'age', 'city'])
person1 = Person(name='John', age=25, city='New York')
print(f"NamedTuple Example: {person1}")

# 2. defaultdict Example
dd = defaultdict(int)
dd['apples'] += 1
dd['bananas'] += 2
print(f"defaultdict Example: {dict(dd)}")

# 3. Counter Example
words = ['apple', 'banana', 'apple', 'orange', 'banana', 'banana']
word_count = Counter(words)
print(f"Counter Example: {word_count}")
    

Explanation of the Program Structure

The program consists of three parts, each demonstrating a specific feature of the collections module:

  1. NamedTuple: We define a Person named tuple with fields ‘name’, ‘age’, and ‘city’. We then create an instance of this named tuple and print it.
  2. defaultdict: We create a defaultdict with int as the default factory function. This means that if a key is accessed that doesn’t exist, it will return 0. We then increment values for ‘apples’ and ‘bananas’ and print the dictionary.
  3. Counter: We create a list of words and use Counter to count the occurrences of each word. We then print the result, showing how many times each word appears.

How to Run the Program

To run this program, follow these steps:

    1. Ensure you have Python 3 installed on your machine.
    2. Create a new file (e.g., collections_example.py) and paste the code into this file.
    3. Open your terminal or command prompt.
    4. Navigate to the directory where your collections_example.py file is located.
    5. Run the program using the following command:
python collections_example.py
  1. The output will be displayed in the terminal, showing examples of each data structure.
© 2025 Learn Programming. All rights reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)