Skip to content

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

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 β†’