Working with Dictionaries and Tuples in Python
Dictionaries and tuples are two essential data structures in Python. They serve different purposes and have unique characteristics. Here’s an overview of both, along with examples that can be executed in various environments like VS Code, Google Colab, Jupyter Notebook, PyCharm, and Anaconda.
1. Dictionaries
A dictionary is a collection of key-value pairs. It is unordered, mutable, and indexed.
Key Features:
- Keys must be unique and immutable (strings, numbers, or tuples).
- Values can be of any data type and can be duplicated.
Example:
# Creating a dictionary
student = {
"name": "Alice",
"age": 21,
"courses": ["Mathematics", "Physics"]
}
# Accessing values
print("Name:", student["name"]) # Output: Alice
print("Age:", student["age"]) # Output: 21
# Adding a new key-value pair
student["GPA"] = 3.8
# Iterating through the dictionary
for key, value in student.items():
print(f"{key}: {value}")
2. Tuples
A tuple is an ordered collection of items. It is immutable, meaning that once it is created, its values cannot be modified.
Key Features:
- Can contain mixed data types.
- Useful for fixed collections of items.
Example:
# Creating a tuple
coordinates = (10.0, 20.0)
# Accessing tuple elements
print("X:", coordinates[0]) # Output: 10.0
print("Y:", coordinates[1]) # Output: 20.0
# Tuples can be unpacked
x, y = coordinates
print("Unpacked Coordinates:", x, y) # Output: Unpacked Coordinates: 10.0 20.0
Watch Video
Running the Code
You can run the above code snippets in any of the following environments:
- VS Code:
- Open a new Python file, copy the code, and run it using the terminal or play button.
- Google Colab:
- Create a new notebook, paste the code into a cell, and run the cell.
- Jupyter Notebook:
- Open a new notebook, paste the code into a cell, and execute it.
- PyCharm:
- Create a new Python project, add a Python file, paste the code, and run it.
- Anaconda:
- Use Jupyter Notebook via Anaconda Navigator, create a new notebook, paste the code, and run it.
Conclusion
Dictionaries and tuples are fundamental data structures in Python that allow you to store and manage data efficiently. The examples provided illustrate how to create and manipulate these structures, and they can be easily executed in various development environments.