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
-
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
:
.
- A dictionary is defined using curly braces
-
Accessing Values:
- Values can be accessed using their corresponding keys.
-
Modifying Dictionaries:
- Adding new key-value pairs.
- Updating existing values.
- Removing key-value pairs.
-
Dictionary Methods:
- Common methods include
get()
,keys()
,values()
,items()
,pop()
,update()
, etc.
- Common methods include
-
Iterating Through Dictionaries:
- Looping through keys, values, or key-value pairs.
Practical Examples
- 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"]
.
- 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.
- 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 to22
. - The key
"courses"
and its value are removed using thedel
statement.
- 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 returnsNone
or a specified default value.keys()
,values()
, anditems()
methods return views of the dictionary’s keys, values, and key-value pairs, respectively.
- 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()
, oritems()
to access keys, values, or key-value pairs.
Practical Exercises
Exercise 1: Create and Modify a Dictionary
Task:
- Create a dictionary named
book
with the following key-value pairs:"title"
:"Python Programming"
"author"
:"John Smith"
"year"
:2021
- Add a new key-value pair
"publisher"
:"Tech Books Publishing"
- Update the
"year"
to2022
- Remove the
"author"
key-value pair - 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:
- Create a dictionary named
employee
with the following key-value pairs:"name"
:"Alice"
"position"
:"Software Engineer"
"salary"
:75000
- Use the
get()
method to retrieve the value of"position"
- Use the
keys()
,values()
, anditems()
methods to print all keys, values, and key-value pairs - 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 aKeyError
. Useget()
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
- Introduction to Python
- Setting Up the Development Environment
- Python Syntax and Basic Data Types
- Variables and Constants
- Basic Input and Output
Module 2: Control Structures
Module 3: Functions and Modules
- Defining Functions
- Function Arguments
- Lambda Functions
- Modules and Packages
- Standard Library Overview
Module 4: Data Structures
Module 5: Object-Oriented Programming
Module 6: File Handling
Module 7: Error Handling and Exceptions
Module 8: Advanced Topics
- Decorators
- Generators
- Context Managers
- Concurrency: Threads and Processes
- Asyncio for Asynchronous Programming
Module 9: Testing and Debugging
- Introduction to Testing
- Unit Testing with unittest
- Test-Driven Development
- Debugging Techniques
- Using pdb for Debugging
Module 10: Web Development with Python
- Introduction to Web Development
- Flask Framework Basics
- Building REST APIs with Flask
- Introduction to Django
- Building Web Applications with Django
Module 11: Data Science with Python
- Introduction to Data Science
- NumPy for Numerical Computing
- Pandas for Data Manipulation
- Matplotlib for Data Visualization
- Introduction to Machine Learning with scikit-learn