Skip to content

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 {}.

user = {
  "name": "Vishnu",
  "age": 25,
  "city": "Surat"
}


๐ŸŽจ 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 โ†’