Mastering Data Aggregation and Formatting in Python

Introduction

Welcome to our lesson on mastering data aggregation and data streams with JSON formatting in Python. In this lesson, we'll start by building a basic sales records aggregator. Then, we'll extend its functionality to handle more complex operations such as filtering, data aggregation, and formatting. By the end of this session, you'll be able to manage and format data streams efficiently.

Starter Task Methods and Their Definitions

To begin, we'll implement a basic sales record aggregator. Here are the methods we'll be focusing on:

  • add_sale(self, sale_id: str, amount: float) -> None - Adds a sale record with a unique identifier sale_id and an amount. If a sale with the same sale_id already exists, it updates the amount.
  • get_sale(self, sale_id: str) -> float | None - Retrieves the sale amount associated with the sale_id. If the sale does not exist, it returns None.
  • delete_sale(self, sale_id: str) -> bool - Deletes the sale record with the given sale_id. Returns True if the sale was deleted and False if the sale does not exist.

Are these methods clear so far? Great! Let's now look at how we would implement them.

Starter Task Solution

Here is the complete code for the starter task:

Python
class SalesAggregator:
    def __init__(self):
        self.sales = {}

    def add_sale(self, sale_id: str, amount: float) -> None:
        self.sales[sale_id] = amount

    def get_sale(self, sale_id: str) -> float | None:
        return self.sales.get(sale_id)

    def delete_sale(self, sale_id: str) -> bool:
        if sale_id in self.sales:
            del self.sales[sale_id]
            return True
        return False

# Example Usage
aggregator = SalesAggregator()

# Add sales
aggregator.add_sale('001', 100.50)
aggregator.add_sale('002', 200.75)

# Get sale
print(aggregator.get_sale('001'))  # Output: 100.5

# Delete sale
print(aggregator.delete_sale('002'))  # Output: True
print(aggregator.get_sale('002'))  # Output: None

Explanation:

  • The __init__ method initializes an empty dictionary to store sales records.
  • The add_sale method adds a new sale or updates the amount for an existing sale ID.
  • The get_sale method retrieves the amount for a given sale ID or returns None if the sale does not exist.
  • The delete_sale method removes the sale record for the given sale ID or returns False if the sale does not exist.

Now that we have our basic aggregator, let's extend it to include more advanced functionalities.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal