📚 A dictionary in Python is a collection of key-value pairs that allows efficient data retrieval. Here's a quick guide to master this essential data structure!
What Are Dictionaries?
Dictionaries are unordered, mutable, and indexed collections. They store data in key-value pairs, where each key is unique and maps to a value.
🔍 Key Features:
- Fast lookups (average O(1) time complexity)
- Flexible keys (can be strings, numbers, or tuples)
- Dynamic resizing
- Nested structures (dictionaries can contain other dictionaries)
Basic Operations
Here are the most common operations you'll use with dictionaries:
Creating a Dictionary
my_dict = {"name": "Alice", "age": 30}
🎨
Accessing Values
print(my_dict["name"]) # Output: Alice
🎨
Updating Values
my_dict["age"] = 31
🎨
Deleting Key-Value Pairs
del my_dict["age"]
🎨
Practical Examples
Let's see dictionaries in action:
🛠️ Example 1:
student = {"id": 1, "score": 95, "subject": "Math"}
print(student["score"]) # Output: 95
🛠️ Example 2:
inventory = {"apples": 10, "bananas": 5, "oranges": 8}
inventory["apples"] += 2 # Update stock
🎨
Common Use Cases
- Storing configuration settings
- Mapping user IDs to names
- Counting frequency of elements
- Implementing hash tables
🔗 For more advanced topics like dictionary methods or nested dictionaries, check out /en/Video_Tutorial/Python/Lists to explore related concepts!
🎨