Working with Dictionaries

Dictionaries store data as key-value pairs, providing fast lookups for structured data. They are essential for representing real-world objects and relationships in code.

Dictionary Fundamentals

student = {
"name": "Alice",
"age": 24,
"major": "Computer Science"
}

Dictionaries:

  • Use curly braces {}
  • Store pairs as key: value
  • Keys must be unique and immutable

Retrieving Data

# Bracket notation
print(student["name"]) # → Alice
# get() method
print(student.get("age")) # → 24
Alice
24

Key differences:

  • [] raises KeyError for missing keys
  • get() returns None (or default) for missing keys

Updating Dictionaries

# Add new entry
student["gpa"] = 3.8
# Update existing
student["age"] = 25

Common Errors

# Accessing non-existent key
print(student["address"]) # KeyError
# Using mutable keys
{[1,2]: "value"} # TypeError

Practical Use: User Database

users = {
"alice2024": {
"name": "Alice Chen",
"email": "alice@example.com",
"premium": True
}
}
user = users.get("alice2024")
if user and user["premium"]:
print(f"Welcome back {user['name']}!")
Welcome back Alice Chen!

Your Task: Contact Lookup

Using contacts = {"Alice": "1234", "Bob": "5678"}:

  1. Retrieve Alice's phone number using dictionary access
  2. Store result in phone variable
  3. Ensure output shows: Alice's phone: 1234

Remember: Choose between bracket notation or get() method.

Section 1/6Dictionary Fundamentals

Dictionary Fundamentals

Dictionaries:Use curly braces {}Store pairs as key: valueKeys must be unique and immutable

Working with Dictionaries

Dictionaries store data as key-value pairs, providing fast lookups for structured data. They are essential for representing real-world objects and relationships in code.

Dictionary Fundamentals

student = {
"name": "Alice",
"age": 24,
"major": "Computer Science"
}

Dictionaries:

  • Use curly braces {}
  • Store pairs as key: value
  • Keys must be unique and immutable

Output:

Click "Check" to run your code.