Python Dictionaries ๐¶
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 โ