Python Dictionaries 🚀
Python Dictionaries is a core Python concept covering master Python Dictionaries. Learn how to store data in key-value pairs, access values by names, and use common dict methods like items(), keys(), and values(). This topic is essential for academic learning, board exam preparation, and developing optimized real-world code.
Mentor's Note: If a List is a group of items found by their Position (0, 1, 2), a Dictionary is a group of items found by their Name (Key). It's like having a search engine inside your data! 💡
🌟 The Scenario: The Smart Phonebook 📞
Imagine you have a modern smartphone.
- The Logic:
- You don't scroll through 500 numbers to find "Mom."
- You search for the Name (The Key). 📦
- The name points instantly to the Phone Number (The Value). 📦
- The Result: You find the information instantly without knowing its position in the list. ✅
📖 Concept Explanation
1. What is a Dictionary?
A dictionary is a collection which is ordered* and changeable. It stores data in key:value pairs.
- Keys must be unique.
- Keys act as the label, Values act as the data.
2. Creating a Dictionary
Dictionaries are written with curly brackets {}.
user = {
"name": "Vishnu",
"age": 25,
"city": "Surat"
}
🎨 Visual Logic: The Key-Value Map
💻 Implementation: The Dictionary Lab
- Python (3.10+)
# 🛒 Scenario: A Product Catalog
# 🚀 Action: Updating and accessing data
product = {
"id": "SKU101",
"brand": "Dell",
"price": 45000
}
# 1. Access by name 🔍
print(product["brand"])
# 2. Update a value 🔄
product["price"] = 42000
# 3. Add a new pair ➕
product["in_stock"] = True
# 4. View all parts 🖼️
print(product.keys()) # Labels only
print(product.values()) # Data only
print(product.items()) # Pairs
# 🛍️ Outcome: A fully updated record
📊 Sample Dry Run (Access)
Input: D = {"A": 1, "B": 2}
| Step | Action | Logic | Result |
|---|---|---|---|
| 1 | D["A"] | Find box labeled "A" | 1 📦 |
| 2 | D.get("C", 0) | Look for "C" (not found) | 0 (Default) |
📉 Complexity Analysis
- Searching by Key: $O(1)$ - Instant! This is why dictionaries are so powerful. ⚡
- Adding/Deleting: $O(1)$ - Very fast.
🎯 Practice Lab 🧪
Task: Create a dictionary named colors where keys are English names ("Red", "Green") and values are Gujarati names ("Lal", "Leelo"). Ask the user for an English color and print the translation.
Hint: print(colors[user_input]). 💡
💡 Industry Context 👔
"In professional web development, we use JSON to send data. Python dictionaries are nearly identical to JSON, making Python the best language for handling web data!"
🔗 Related Topics
← Back: Sets | Next: Data Comparisons →