Python Dictionaries πΒΆ
Prerequisites: Python Lists
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 {}.
π¨ Visual Logic: The Key-Value MapΒΆ
graph LR
subgraph Keys: ["The Labels π·οΈ"]
K1[name]
K2[age]
end
subgraph Values: ["The Data π¦"]
V1["Vishnu"]
V2[25]
end
K1 --> V1
K2 --> V2
π» Implementation: The Dictionary LabΒΆ
# π 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: The Translation Dictionary
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!"
β Back: Sets | Next: Data Comparisons β