Exploring Python Dictionaries

In Python, a dictionary is a powerful and flexible data structure that allows you to store key-value pairs. Let's delve into dictionaries in a beginner-friendly manner:


  • Understanding Dictionaries:
  • A dictionary in Python is an unordered collection of items where each item is stored as a key-value pair. Unlike sequences like lists or tuples, where elements are accessed by their position, elements in a dictionary are accessed by their keys.

  • Creating Dictionaries:
  • You can create a dictionary by enclosing key-value pairs within curly braces {}. Each key-value pair is separated by a colon :. Here's an example:

    my_dict = {"name": "Alice", "age": 30, "city": "New York"}

  • Accessing Dictionary Elements:
  • You can access the value associated with a key in a dictionary using square brackets []. Here's an example:

    print(my_dict["name"]) # Output: Alice
    print(my_dict["age"]) # Output: 30

  • Dictionary Methods:
  • keys(): Returns a view of all keys in the dictionary.
    values(): Returns a view of all values in the dictionary.
    items(): Returns a view of all key-value pairs in the dictionary as tuples.

    print(my_dict.keys()) # Output: dict_keys(['name', 'age', 'city'])
    print(my_dict.values()) # Output: dict_values(['Alice', 30, 'New York'])
    print(my_dict.items()) # Output: dict_items([('name', 'Alice'), ('age', 30), ('city', 'New York')])

  • Modifying Dictionaries:
  • You can modify dictionaries by adding, updating, or removing key-value pairs.

    Adding: You can add a new key-value pair to a dictionary using square brackets [].
    Updating: You can update the value associated with a key by assigning a new value to that key.
    Removing: You can remove a key-value pair from a dictionary using the del keyword or the pop() method.

    tuple1 = (1, 2, 3)
    tuple2 = (4, 5, 6)
    concatenated_tuple = tuple1 + tuple2 # Output: (1, 2, 3, 4, 5, 6)
    repeated_tuple = tuple1 * 3 # Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)
  • Real-life Examples:
  • 1. Question: You are tasked with managing the inventory of a grocery store. Create a Python program that allows you to track the quantity of various items in stock and update the inventory after each sale.

    # Initialize inventory dictionary
    inventory = {
    "apple": 20,
    "banana": 15,
    "orange": 30
    }

    # Function to update inventory after a sale
    def update_inventory(item, quantity_sold):
    if item in inventory:
    inventory[item] -= quantity_sold
    print("Inventory updated. Remaining quantity of", item, ":", inventory[item])
    else:
    print("Item not found in inventory.")

    # Example usage
    update_inventory("apple", 5) # 5 apples sold

    2. Question: You need to calculate the average grade of students in a class. Create a Python program that stores student names and their corresponding grades and calculates the average grade for the class.

    # Dictionary representing student names and grades
    student_grades = {
    "Alice": 85,
    "Bob": 90,
    "Charlie": 78,
    "David": 92
    }

    # Function to calculate average grade
    def calculate_average_grade(grades):
    total = sum(grades.values())
    average = total / len(grades)
    return average

    # Example usage
    average_grade = calculate_average_grade(student_grades)
    print("Average grade:", average_grade)

    3. Question: Implement a simple user authentication system using Python dictionaries. The program should prompt users to enter their username and password and verify if the credentials match the records stored in the dictionary.

    # Dictionary representing user credentials
    user_credentials = {
    "user1": "password123",
    "user2": "abc@123",
    "user3": "qwerty"
    }

    # Function to authenticate user
    def authenticate_user(username, password):
    if username in user_credentials and user_credentials[username] == password:
    print("Authentication successful. Welcome,", username)
    else:
    print("Authentication failed. Invalid username or password.")

    # Example usage
    authenticate_user("user2", "abc@123") # Valid credentials

    4. Question: Create a Python program that allows users to search for products in a catalog by their name. The program should retrieve and display the price of the product if found, or indicate if the product is not available.

    # Dictionary representing product catalog with prices
    product_catalog = {
    "apple": 1.99,
    "banana": 0.99,
    "orange": 2.49
    }

    # Function to search for a product in the catalog
    def search_product(product_name):
    if product_name in product_catalog:
    print("Price of", product_name, ":", product_catalog[product_name])
    else:
    print(product_name, "is not available in the catalog.")

    # Example usage
    search_product("banana") # Output: Price of banana: 0.99

  • Advantages of Dictionaries:
  • Fast Lookup: Dictionary lookups are very fast, even for large dictionaries.
    Flexible: Dictionaries can store heterogeneous data types and can be nested.
    Key-Value Mapping: Dictionaries provide a convenient way to map keys to values, making them ideal for many programming tasks.


  • Summary:
  • Python dictionaries are versatile data structures that allow you to store and manipulate key-value pairs efficiently. Whether you need to store configuration settings, count occurrences of elements, or represent complex data relationships, dictionaries provide a flexible and powerful solution for a wide range of programming tasks.