Dictionaries in Python are a collection of key-value pairs. Each key is unique, and it maps to a value. Dictionaries are mutable, meaning they can be changed after creation. They are incredibly useful for storing and managing data that is associated with unique identifiers.

Key Concepts

  1. Definition and Syntax:

    • A dictionary is defined using curly braces {}.
    • Key-value pairs are separated by commas.
    • Keys and values are separated by a colon :.
  2. Accessing Values:

    • Values can be accessed using their corresponding keys.
  3. Modifying Dictionaries:

    • Adding new key-value pairs.
    • Updating existing values.
    • Removing key-value pairs.
  4. Dictionary Methods:

    • Common methods include get(), keys(), values(), items(), pop(), update(), etc.
  5. Iterating Through Dictionaries:

    • Looping through keys, values, or key-value pairs.

Practical Examples

  1. Creating a Dictionary

# Creating a dictionary
student = {
    "name": "John Doe",
    "age": 21,
    "courses": ["Math", "Computer Science"]
}

print(student)

Explanation:

  • The dictionary student contains three key-value pairs.
  • The keys are "name", "age", and "courses".
  • The values are "John Doe", 21, and a list ["Math", "Computer Science"].

  1. Accessing Values

# Accessing values using keys
print(student["name"])  # Output: John Doe
print(student["age"])   # Output: 21
print(student["courses"])  # Output: ['Math', 'Computer Science']

Explanation:

  • Values are accessed using square brackets [] with the key inside.

  1. Modifying Dictionaries

# Adding a new key-value pair
student["grade"] = "A"

# Updating an existing value
student["age"] = 22

# Removing a key-value pair
del student["courses"]

print(student)

Explanation:

  • A new key "grade" is added with the value "A".
  • The value of the key "age" is updated to 22.
  • The key "courses" and its value are removed using the del statement.

  1. Dictionary Methods

# Using get() method
print(student.get("name"))  # Output: John Doe
print(student.get("address", "Not Found"))  # Output: Not Found

# Using keys(), values(), and items() methods
print(student.keys())    # Output: dict_keys(['name', 'age', 'grade'])
print(student.values())  # Output: dict_values(['John Doe', 22, 'A'])
print(student.items())   # Output: dict_items([('name', 'John Doe'), ('age', 22), ('grade', 'A')])

Explanation:

  • get() method retrieves the value for a given key. If the key does not exist, it returns None or a specified default value.
  • keys(), values(), and items() methods return views of the dictionary’s keys, values, and key-value pairs, respectively.

  1. Iterating Through Dictionaries

# Iterating through keys
for key in student.keys():
    print(key)

# Iterating through values
for value in student.values():
    print(value)

# Iterating through key-value pairs
for key, value in student.items():
    print(f"{key}: {value}")

Explanation:

  • You can loop through the dictionary using keys(), values(), or items() to access keys, values, or key-value pairs.

Practical Exercises

Exercise 1: Create and Modify a Dictionary

Task:

  1. Create a dictionary named book with the following key-value pairs:
    • "title": "Python Programming"
    • "author": "John Smith"
    • "year": 2021
  2. Add a new key-value pair "publisher": "Tech Books Publishing"
  3. Update the "year" to 2022
  4. Remove the "author" key-value pair
  5. Print the final dictionary

Solution:

# Step 1: Create the dictionary
book = {
    "title": "Python Programming",
    "author": "John Smith",
    "year": 2021
}

# Step 2: Add a new key-value pair
book["publisher"] = "Tech Books Publishing"

# Step 3: Update the year
book["year"] = 2022

# Step 4: Remove the author key-value pair
del book["author"]

# Step 5: Print the final dictionary
print(book)

Exercise 2: Dictionary Methods and Iteration

Task:

  1. Create a dictionary named employee with the following key-value pairs:
    • "name": "Alice"
    • "position": "Software Engineer"
    • "salary": 75000
  2. Use the get() method to retrieve the value of "position"
  3. Use the keys(), values(), and items() methods to print all keys, values, and key-value pairs
  4. Iterate through the dictionary and print each key-value pair in the format key: value

Solution:

# Step 1: Create the dictionary
employee = {
    "name": "Alice",
    "position": "Software Engineer",
    "salary": 75000
}

# Step 2: Use the get() method
print(employee.get("position"))  # Output: Software Engineer

# Step 3: Use keys(), values(), and items() methods
print(employee.keys())    # Output: dict_keys(['name', 'position', 'salary'])
print(employee.values())  # Output: dict_values(['Alice', 'Software Engineer', 75000])
print(employee.items())   # Output: dict_items([('name', 'Alice'), ('position', 'Software Engineer'), ('salary', 75000)])

# Step 4: Iterate through the dictionary
for key, value in employee.items():
    print(f"{key}: {value}")

Common Mistakes and Tips

  • Using mutable types as dictionary keys: Only immutable types (like strings, numbers, and tuples) can be used as dictionary keys.
  • Accessing non-existent keys: Using dict[key] to access a non-existent key will raise a KeyError. Use get() to avoid this.
  • Modifying a dictionary while iterating: Avoid modifying the dictionary (adding or removing items) while iterating through it, as it can lead to unexpected behavior.

Conclusion

Dictionaries are a powerful and flexible data structure in Python, allowing you to store and manage data efficiently with key-value pairs. Understanding how to create, modify, and utilize dictionaries is essential for effective Python programming. In the next section, we will explore sets, another important data structure in Python.

Python Programming Course

Module 1: Introduction to Python

Module 2: Control Structures

Module 3: Functions and Modules

Module 4: Data Structures

Module 5: Object-Oriented Programming

Module 6: File Handling

Module 7: Error Handling and Exceptions

Module 8: Advanced Topics

Module 9: Testing and Debugging

Module 10: Web Development with Python

Module 11: Data Science with Python

Module 12: Final Project

© Copyright 2024. All rights reserved