Dictionary Basics
What is a Dictionary?
In Python, a dictionary is a powerful and flexible data structure that stores key-value pairs. Unlike lists, dictionaries use unique keys to access and organize data, providing an efficient way to manage and retrieve information.
Key Characteristics
Dictionaries in Python have several important 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 |
| Flexible Value Types |
Values can be of any data type |
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", department="IT", salary=5000)
## Method 3: Creating an empty dictionary
empty_dict = {}
Accessing Dictionary Elements
Dictionaries provide flexible methods to access and manipulate data:
## Accessing values by key
print(student["name"]) ## Output: Alice
## Using get() method (safer approach)
print(student.get("age", "Not found")) ## Output: 22
Dictionary Operations
graph TD
A[Dictionary Creation] --> B[Adding Elements]
B --> C[Modifying Elements]
C --> D[Removing Elements]
D --> E[Checking Key Existence]
Basic Operations Example
## Adding a new key-value pair
student["email"] = "alice@example.com"
## Updating an existing value
student["age"] = 23
## Removing an element
del student["grade"]
## Checking if a key exists
if "name" in student:
print("Name is present")
Dictionary Methods
Python provides several built-in methods for dictionary manipulation:
keys(): Returns all keys
values(): Returns all values
items(): Returns key-value pairs
clear(): Removes all elements
copy(): Creates a shallow copy
Use Cases
Dictionaries are ideal for:
- Storing configuration settings
- Managing user profiles
- Representing complex data structures
- Counting and grouping data
By understanding these basics, you'll be well-equipped to work with dictionaries in Python. LabEx recommends practicing these concepts to gain proficiency.