Understanding Dictionaries
What are Dictionaries?
In Python, dictionaries are versatile and powerful data structures that store key-value pairs. They provide an efficient way to map unique keys to specific values, allowing fast retrieval and manipulation of data.
Basic Dictionary Characteristics
Dictionaries in Python have several key characteristics:
Characteristic |
Description |
Mutable |
Can be modified after creation |
Unordered |
Keys are not stored in a specific order |
Unique Keys |
Each key must be unique |
Key Types |
Keys must be immutable (strings, numbers, tuples) |
Creating Dictionaries
## Empty dictionary
empty_dict = {}
## Dictionary with initial values
student = {
"name": "Alice",
"age": 22,
"courses": ["Python", "Data Science"]
}
## Using dict() constructor
another_dict = dict(name="Bob", age=25)
Dictionary Operations
Accessing Values
## Direct key access
print(student["name"]) ## Output: Alice
## Using get() method (safer)
print(student.get("email", "Not found"))
Adding and Modifying Elements
## Adding new key-value pair
student["email"] = "[email protected]"
## Updating existing value
student["age"] = 23
Nested Dictionaries
company = {
"employees": {
"developer": {"name": "Charlie", "skills": ["Python", "Django"]},
"designer": {"name": "Diana", "skills": ["UI/UX"]}
}
}
Dictionary Comprehensions
## Creating 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}
Workflow of Dictionary Operations
graph TD
A[Create Dictionary] --> B{Dictionary Operations}
B --> C[Access Values]
B --> D[Modify Values]
B --> E[Add/Remove Elements]
B --> F[Iterate Through Dictionary]
Key Takeaways
- Dictionaries are flexible, mutable data structures
- They provide fast key-based access to values
- Useful for representing complex, structured data
- Support various operations like adding, modifying, and accessing elements
At LabEx, we recommend practicing dictionary operations to become proficient in Python data manipulation.