Introduction:
In Python, a dictionary is a versatile and powerful data structure used to store information as key-value pairs. Unlike lists and tuples that use an index to access elements, dictionaries allow you to access values using unique keys. This makes them an excellent choice for storing and organising data where each piece of information is associated with a specific label (the key).
Think of a dictionary like a real-world dictionary where you use a word (the key) to find its definition (the value). In programming, we often use dictionaries to store structured data, such as student records, product details, or settings configurations.
Key Features of Dictionaries:
- Key-Value Pairs: Each entry consists of a key and its associated value.
- Unique Keys: Each key in a dictionary must be unique, while values can be repeated.
- Mutable: You can modify dictionaries by adding, updating, or deleting key-value pairs.
Real-World Example:
Imagine creating a system to store student data. Each student has a name, age, and grade. Using a dictionary, we can store this information as key-value pairs:
<pre class="code"> student = { "name": "Alice", "age": 14, "grade": "A" } </pre>
In this dictionary:
- The keys are
"name"
,"age"
, and"grade"
. - The values are
"Alice"
,14
, and"A"
.
This structure allows us to easily access or update any student’s data by referencing their keys.
Accessing Values in a Dictionary
To access a value in a dictionary, you use the key inside square brackets. For example, to get the student’s name:
student = { "name": "Alice", "age": 14, "grade": "A" } print(student["name"]) # Outputs: Alice
Let’s try accessing values from a dictionary:
In this example, we accessed the values for "name"
and "grade"
from the student
dictionary.
Adding and Updating Key-Value Pairs
Dictionaries are mutable, which means you can add new key-value pairs or update existing ones. For example, we can add a new key for the student's school or update their grade:
student = { "name": "Alice", "age": 14, "grade": "A" } # Add a new key-value pair for 'school' student["school"] = "Greenwood High" # Update the 'grade' student["grade"] = "A+" print(student)
Try adding and updating dictionary elements in the following code:
Notice how we added "school": "Greenwood High"
and updated the grade to "A+"
.
Removing Items from a Dictionary
You can remove a key-value pair from a dictionary using the del
statement or the pop()
method. Let’s see an example:
student = { "name": "Alice", "age": 14, "grade": "A" } # Remove the 'age' key del student["age"] print(student) # Outputs: {'name': 'Alice', 'grade': 'A'}
Let’s try removing an element from a dictionary:
In this case, we removed the "age"
key, and the dictionary now contains only "name"
and "grade"
.
Checking if a Key Exists
You can check if a key exists in a dictionary using the in
keyword:
if "name" in student: print("Name exists in the dictionary")
Try checking if a key exists:
This example checks if "name"
exists and whether "school"
does not exist in the dictionary.
Conclusion:
Dictionaries are a powerful and flexible way to store structured data using key-value pairs. They are perfect for situations where you need to label data (like records or objects) rather than rely on position. You can access values by key, add or update data, and check if keys exist.
Predict:
Look at the following code. Can you predict what the output will be when the key
student = { "name": "Alice", "age": 14, "grade": "A" } print(student["grade"])
Since the dictionary uses keys to access values, think about what the code will print when we use the key "grade"
.
Run:
Let’s run an example where we create a dictionary to store information about a book and then access different values by using their keys.
When you run this code, observe how the dictionary stores different pieces of information, and how each value is accessed by its key.
Investigate:
Now let's investigate further. Here’s an example where we add a new key-value pair to an existing dictionary. What do you think will happen?
Instructions: Run this code and observe how the dictionary is updated. Try adding other key-value pairs (e.g., 'city': 'London'
) and see how Python dynamically updates the dictionary.
Modify:
Now it’s your turn to modify a piece of code. Below is an incomplete dictionary for a car, but the "colour"
key is missing. Can you add "colour": "red"
to the dictionary and print the updated car information?
Hint: Use the key "colour"
to add the value "red"
to the dictionary.