π Dictionary in Python
πΉ What is a Dictionary in Python?A dictionary in Python is a built-in data structure used to store data in keyβvalue pairs. Dictionaries are unordered (insertion-ordered from Python 3.7+), mutable, and do not allow duplicate keys.
π Dictionaries are widely used for fast data lookup and structured data storage.
β Why Use Dictionaries?
- Fast access using keys
- Store structured and related data
- Flexible and dynamic size
- Efficient for lookups and mappings
π Creating a Dictionary
student = {
"name": "John",
"age": 21,
"course": "Python"
}
πΈ Empty Dictionary
empty_dict = {}
π Types of Dictionaries (Common Usage)
1οΈβ£ Simple Dictionary
marks = {"math": 90, "science": 85}
2οΈβ£ Mixed Dictionary
data = {"id": 101, "active": True, "score": 9.5}
3οΈβ£ Nested Dictionary
employee = {
"name": "Alice",
"details": {"age": 30, "dept": "IT"}
}
π Accessing Dictionary Elements
print(student["name"])
print(student.get("age"))
β get() avoids errors if the key is missing.
π Modifying a Dictionary
Dictionaries are mutable.
student["age"] = 22
student["city"] = "New York"
π Removing Elements
student.pop("city")
del student["course"]
student.clear()
π Dictionary Methods
| Method | Description |
|---|---|
| keys() | Returns all keys |
| values() | Returns all values |
| items() | Returns key-value pairs |
| update() | Updates dictionary |
| pop() | Removes a key |
| clear() | Removes all items |
student.keys()
student.values()
student.items()
π Looping Through a Dictionary
for key, value in student.items():
print(key, value)
π Dictionary Comprehension
Create dictionaries in a single line.
squares = {x: x*x for x in range(1, 6)}
π Checking Keys and Values
"name" in student
21 in student.values()
π Copying a Dictionary
new_student = student.copy()
β Advantages of Dictionaries
- Fast data access
- Flexible and dynamic
- Easy to store structured data
- Highly efficient for lookups
β Disadvantages of Dictionaries
- Uses more memory
- Keys must be immutable
- No direct indexing
π Dictionary vs List (Quick Comparison)
| Feature | Dictionary | List |
|---|---|---|
| Storage | KeyβValue | Index-based |
| Access Speed | Faster | Slower |
| Mutability | Mutable | Mutable |
π Real-World Use Cases
- Storing user profiles
- Database records
- Configuration settings
- JSON data handling
- API responses