Python Tutorial: Organizing Key-Value Data with Dictionaries
Dictionaries in Python are powerful data structures used to store data in <a href="Read More“>key-value pairs. Think of them like a real-world dictionary where you look up a word (the key) to find its definition (the value). Dictionaries are mutable, meaning you can change their contents after they’ve been created. They are built-in to Python and provide a convenient way to organize related data.
Understanding Dictionaries
A dictionary is defined using curly braces `{}`. Inside the braces, you have key-value pairs separated by commas. Each key-value pair consists of a key and a value, separated by a colon `:`. Keys must be unique within a dictionary, and they are typically strings, but can also be numbers or tuples. Values can be any Python data type.
Example 1: Creating and Accessing a Simple Dictionary
Let’s create a dictionary called `student` to store information about a student’s name and grade.
student = {
"name": "Alice",
"grade": 95,
"major": "Computer Science"
}
# Accessing values using keys
print(student["name"])
print(student["grade"])
print(student["major"])
In this example, we first created a dictionary named `student`. We then used the square bracket notation (`[]`) to access the values associated with the keys “name”, “grade”, and “major”. When we try to access a key that doesn’t exist, Python raises a `KeyError`. To avoid this, you should always check if a key exists before trying to access its value, or use the `get()` method.
Common Beginner Mistake: Forgetting the square brackets `[]` when trying to access a dictionary value. Correction: Remember to use `student[“name”]` instead of `student.name` (the latter will throw an error if “name” is not a key).
Mathematical Calculation: Let’s perform a simple calculation: grade = student["grade"] + 5. This adds 5 to the student’s grade (95). The result is 100. This is a basic arithmetic operation that demonstrates Python’s ability to perform calculations.
Output:
Alice
95
Computer Science
Example 2: Adding and Modifying Dictionary Elements
Dictionaries are mutable, so we can add new key-value pairs and modify existing ones.
student = {
"name": "Alice",
"grade": 95,
"major": "Computer Science"
}
# Adding a new key-value pair
student["gpa"] = 3.8
# Modifying an existing value
student["grade"] = 98
print(student)
Here, we added a new key-value pair “gpa” with a value of 3.8. We then modified the value associated with the “grade” key to 98. The `print(student)` statement displays the entire dictionary, which now includes the added key-value pair and the updated grade value.
Output:
{'name': 'Alice', 'grade': 98, 'major': 'Computer Science', 'gpa': 3.8}
Example 3: Using the `get()` Method and Error Handling
The `get()` method provides a safer way to access dictionary values. If the key doesn’t exist, it returns `None` by default, or you can specify a default value to return instead.
student = {
"name": "Alice",
"grade": 95
}
# Accessing a key that might not exist
city = student.get("city")
print(city)
# Accessing a key that might not exist with a default value
country = student.get("country", "USA")
print(country)
In this example, `student.get(“city”)` returns `None` because the key “city” is not present in the dictionary. `student.get(“country”, “USA”)` returns “USA” because the key “country” is not present, and we provided a default value of “USA”. Using `get()` prevents `KeyError` exceptions.
Output:
None
USA
Conclusion
Dictionaries are a fundamental data structure in Python. They allow you to organize data in a structured and efficient way, making them ideal for storing and retrieving data based on unique keys. Remember to handle potential `KeyError` exceptions using the `get()` method or by checking key existence before accessing values.



Leave a Reply