Introduction

Welcome to our Python data structures revision! Today, we will delve deeply into Python Dictionaries. Much like a bookshelf, dictionaries allow you to quickly select the book (value) you desire by reading its label (key). They are vital to Python for quickly accessing values using keys, as well as efficient key insertion and deletion. So, let's explore Python dictionaries for a clearer understanding of these concepts.

Python Dictionaries

Our journey starts with Python dictionaries, a pivotal data structure that holds data as key-value pairs. Imagine storing your friend's contact info in such a way that allows you to search for your friend's name (the key) and instantly find their phone number (the value).

class PhoneBook:

    def __init__(self):
        # An empty dictionary
        self.contacts = {}

    def add_contact(self, name, phone_number):
        # Method to add a contact
        self.contacts[name] = phone_number

    def get_phone_number(self, name):
        # Method to retrieve contact's phone number, or None, if it's in contacts
        return self.contacts.get(name, None)

# Create a PhoneBook instance
phone_book = PhoneBook()

# Add contacts
phone_book.add_contact("Alice", "123-456-7890")
phone_book.add_contact("Bob", "234-567-8901")
print(phone_book.get_phone_number("Alice")) # Output: "123-456-7890"
print(phone_book.get_phone_number("Bobby")) # Output: None

In the above code, we create a PhoneBook class that uses a dictionary to store contacts. As you can see, dictionaries simplify the processes of adding, modifying, and accessing information with unique keys.

Operations in Dictionaries

Python dictionaries enable a variety of operations for manipulating data, such as setting, getting, and deleting key-value pairs. Understanding these operations is crucial for efficient data handling in Python.

To add or update entries in a dictionary, you directly assign a value to a key. If the key exists, the value is updated; if not, a new key-value pair is added. This flexibility allows for dynamic updates and additions to the dictionary without needing a predefined structure.

The get operation is used to retrieve the value associated with a specific key. It provides a safe way to access values since it allows specifying a default value if the key does not exist, preventing errors that would arise from attempting to access a non-existent key.

Deleting an entry is done using the del statement followed by the key. This operation removes the specified key-value pair from the dictionary, which is essential for managing the contents of the dictionary actively.

Let’s see how these operations work in the context of a Task Manager class:

class TaskManager:

    def __init__(self):
        # Initialize with an empty dictionary
        self.tasks = {}

    def add_update_task(self, task_name, status):
        # Add a new task or update an existing task
        self.tasks[task_name] = status

    def get_task_status(self, task_name):
        # Retrieve the status of a task; Returns "Not Found" if the task does not exist
        return self.tasks.get(task_name, "Not Found")

    def delete_task(self, task_name):
        # Removes a task using its name
        if task_name in self.tasks:
            del self.tasks[task_name]
        else:
            print(f"Task '{task_name}' not found.")

# Test the TaskManager class
my_tasks = TaskManager()
my_tasks.add_update_task("Buy Milk", "Pending")
print(my_tasks.get_task_status("Buy Milk"))  # Output: Pending
my_tasks.add_update_task("Buy Milk", "Completed")
print(my_tasks.get_task_status("Buy Milk"))  # Output: Completed

my_tasks.delete_task("Buy Milk")
print(my_tasks.get_task_status("Buy Milk"))  # Output: Not Found

This example showcases how to leverage dictionary operations in Python to effectively manage data by adding, updating, retrieving, and deleting entries through a simulated Task Manager application.

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