Applying Data Filtering and Aggregation in User Data Management

Introduction

Welcome to today's lesson on applying data filtering and aggregation in a real-world scenario using a user management system. We'll start by building a foundational structure that can handle basic user operations. Then, we'll expand it by introducing more advanced functionalities that allow filtering and aggregating user data.

Starter Task Methods

In our starter task, we will implement a class that manages basic operations on a collection of user data, specifically handling adding new users, retrieving user profiles, and updating user profiles.

Here are the starter task methods:

  • add_user(self, user_id: str, age: int, country: str, subscribed: bool) -> bool - adds a new user with the specified attributes. Returns True if the user was added successfully and False if a user with the same user_id already exists.
  • get_user(self, user_id: str) -> dict[str, int | str | bool] | None - returns the user's profile as a dictionary if the user exists; otherwise, returns None.
  • update_user(self, user_id: str, age: int | None, country: str | None, subscribed: bool | None) -> bool - updates the user's profile based on non-None parameters. Returns True if the user exists and was updated, False otherwise.

Solution for the Starter Task

Here is the implementation of our starter task:

class UserManager:
    def __init__(self):
        self.users = {}
    
    def add_user(self, user_id: str, age: int, country: str, subscribed: bool) -> bool:
        if user_id in self.users:
            return False
        self.users[user_id] = {"age": age, "country": country, "subscribed": subscribed}
        return True

    def get_user(self, user_id: str) -> dict[str, int | str | bool] | None:
        return self.users.get(user_id, None)

    def update_user(self, user_id: str, age: int | None, country: str | None, subscribed: bool | None) -> bool:
        if user_id not in self.users:
            return False
        if age is not None:
            self.users[user_id]["age"] = age
        if country is not None:
            self.users[user_id]["country"] = country
        if subscribed is not None:
            self.users[user_id]["subscribed"] = subscribed
        return True

# Example usage
um = UserManager()
print(um.add_user("u1", 25, "USA", True))  # True
print(um.add_user("u2", 30, "Canada", False))  # True
print(um.add_user("u1", 22, "Mexico", True))  # False
print(um.get_user("u1"))  # {"age": 25, "country": "USA", "subscribed": True}
print(um.update_user("u1", 26, None, None))  # True
print(um.update_user("u3", 19, "UK", False))  # False

This implementation covers all our starter methods. Let's move forward and introduce more complex 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