Dictionary Basics
What is a Dictionary?
In Python, a dictionary is a versatile and powerful data structure that stores key-value pairs. Unlike lists that use numeric indices, dictionaries use unique keys to access and manage data efficiently.
Key Characteristics
Characteristic |
Description |
Mutable |
Can be modified after creation |
Unordered |
No fixed order of elements |
Key-Value Pairs |
Each element consists of a key and its corresponding value |
Unique Keys |
Each key must be unique |
Creating Dictionaries
There are multiple ways to create dictionaries in Python:
## Method 1: Using curly braces
student = {"name": "Alice", "age": 22, "grade": "A"}
## Method 2: Using dict() constructor
teacher = dict(name="Bob", subject="Python", experience=5)
## Method 3: Using dict comprehension
squares = {x: x**2 for x in range(5)}
Basic Dictionary Operations
Adding and Modifying Elements
## Adding a new key-value pair
student["email"] = "[email protected]"
## Modifying an existing value
student["age"] = 23
Accessing Elements
## Using square bracket notation
name = student["name"]
## Using .get() method (safer)
age = student.get("age", "Not specified")
Common Dictionary Methods
flowchart TD
A[Dictionary Methods] --> B[keys()]
A --> C[values()]
A --> D[items()]
A --> E[pop()]
A --> F[update()]
Practical Example
## Demonstrating dictionary methods
courses = {"Math": 95, "Science": 88, "English": 92}
## Accessing keys
print(courses.keys()) ## dict_keys(['Math', 'Science', 'English'])
## Accessing values
print(courses.values()) ## dict_values([95, 88, 92])
## Removing and returning a value
removed_score = courses.pop("Math")
Error-Prone Scenarios
- Accessing non-existent keys
- Duplicate key definitions
- Incorrect key types
By understanding these basics, you'll be well-prepared to work with dictionaries in Python and avoid common pitfalls. At LabEx, we recommend practicing these concepts to build strong programming skills.