Dictionary Fundamentals
What is a Python Dictionary?
A Python dictionary is a powerful, built-in data structure that stores key-value pairs. It allows you to create a collection of unique keys mapped to specific values, providing an efficient way to organize and retrieve data.
Basic Dictionary Creation
## Creating an empty dictionary
empty_dict = {}
another_empty_dict = dict()
## Dictionary with initial values
student = {
"name": "Alice",
"age": 22,
"major": "Computer Science"
}
Key Characteristics
Unique Keys
Dictionaries require unique keys. If you try to insert a duplicate key, it will replace the previous value.
## Duplicate key example
user = {
"username": "john_doe",
"username": "new_john" ## This will override the previous value
}
print(user) ## Output: {"username": "new_john"}
Key Types
Dictionary keys must be immutable types:
- Strings
- Numbers
- Tuples
- Frozensets
## Valid dictionary keys
valid_dict = {
"name": "LabEx",
42: "Answer",
(1, 2): "Coordinate"
}
Dictionary Operations
Adding and Updating Elements
## Creating a dictionary
profile = {"name": "John"}
## Adding a new key-value pair
profile["age"] = 30
## Updating an existing value
profile["name"] = "John Doe"
Accessing Values
## Accessing values by key
print(profile["name"]) ## Output: John Doe
## Using get() method (safer)
print(profile.get("city", "Not Found")) ## Returns "Not Found" if key doesn't exist
Dictionary Methods
Method |
Description |
Example |
keys() |
Returns all keys |
profile.keys() |
values() |
Returns all values |
profile.values() |
items() |
Returns key-value pairs |
profile.items() |
Dictionary Comprehension
## Creating a dictionary using comprehension
squares = {x: x**2 for x in range(6)}
## Result: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
graph TD
A[Dictionary Lookup] --> B{Key Exists?}
B -->|Yes| C[Return Value]
B -->|No| D[Raise KeyError]
Best Practices
- Use meaningful and consistent key names
- Prefer
.get()
method for safer access
- Use dictionary comprehensions for concise creation
- Consider using
defaultdict
for complex scenarios
By understanding these fundamentals, you'll be well-equipped to leverage Python dictionaries effectively in your LabEx programming projects.