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 allow you to use any immutable type as a key, providing a flexible way to organize and access data.
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
employee = dict(name="Bob", position="Developer", salary=5000)
## Method 3: Creating an empty dictionary
empty_dict = {}
Dictionary Characteristics
Characteristic |
Description |
Mutable |
Can be modified after creation |
Unordered |
Keys are not in a specific order |
Key Uniqueness |
Each key must be unique |
Key Types |
Keys must be immutable (strings, numbers, tuples) |
Accessing Dictionary Values
## Direct access
print(student["name"]) ## Output: Alice
## Using get() method (safer)
print(student.get("age")) ## Output: 22
Dictionary Operations
## Adding/Updating values
student["city"] = "New York"
## Removing items
del student["grade"]
## Checking key existence
if "name" in student:
print("Name exists")
Dictionary Workflow
graph TD
A[Create Dictionary] --> B{Add/Modify Values}
B --> |Add Key| C[Insert New Key-Value Pair]
B --> |Update Value| D[Modify Existing Value]
B --> |Delete Key| E[Remove Key-Value Pair]
By understanding these basics, you'll be well-prepared to work with dictionaries safely and efficiently in Python. LabEx recommends practicing these concepts to build strong programming skills.