Dictionary Key Basics
What is a Dictionary in Python?
A dictionary in Python is a powerful data structure that stores key-value pairs. Unlike lists that use numeric indices, dictionaries allow you to use any immutable type (such as strings, numbers, or tuples) as keys to access corresponding values.
Basic Dictionary Operations
Creating a Dictionary
## Creating an empty dictionary
student = {}
## Creating a dictionary with initial values
student = {
"name": "Alice",
"age": 25,
"courses": ["Python", "Data Science"]
}
Accessing Dictionary Values
## Accessing values using keys
print(student["name"]) ## Outputs: Alice
## Using get() method (safer approach)
print(student.get("age")) ## Outputs: 25
Key Characteristics
Key Characteristic |
Description |
Unique Keys |
Each key in a dictionary must be unique |
Immutable Keys |
Keys must be of immutable types |
Mutable Values |
Values can be of any type |
Key Lookup Workflow
graph TD
A[Dictionary Key Lookup] --> B{Key Exists?}
B -->|Yes| C[Return Value]
B -->|No| D[Raise KeyError]
Common Key Types
## String keys
person = {"name": "John", "age": 30}
## Integer keys
scores = {1: "First", 2: "Second"}
## Tuple keys
coordinates = {(0, 0): "Origin", (1, 1): "Point"}
Understanding Key Errors
When you try to access a non-existent key, Python raises a KeyError
. This is a critical concept to understand for robust dictionary handling in Python.
## This will raise a KeyError
try:
value = student["address"]
except KeyError:
print("Key does not exist in the dictionary")
At LabEx, we recommend always being prepared to handle potential key lookup errors in your Python programming.