šŸ

Dictionaries: Key-Value Pairs

Beginner
90 XP
40 min
Lesson Content

Dictionaries: Storing Key-Value Pairs

Dictionaries are collections of key-value pairs. They're perfect for storing related data where each item has a unique identifier (key).

Creating Dictionaries

Dictionaries use curly braces with key:value pairs:

# Empty dictionary
my_dict = {}
# Dictionary with data
student = { "name": "Alice", "age": 20, "grade": "A" }
# Using dict() constructor
student = dict(name="Alice", age=20, grade="A")

Accessing Values

Access values using keys:

student = {"name": "Alice", "age": 20}

# Access by key
print(student["name"]) # Alice print(student["age"]) # 20
# Using get() (safer, returns None if key doesn't exist)
print(student.get("name")) # Alice print(student.get("grade")) # None (key doesn't exist) print(student.get("grade", "N/A")) # N/A (default value)

Modifying Dictionaries

Add, update, or remove items:

student = {"name": "Alice", "age": 20}

# Add new key-value pair
student["grade"] = "A"
# Update existing value
student["age"] = 21
# Remove item student.pop("grade") # Remove and return value del student["age"] # Remove item

Dictionary Methods

student = {"name": "Alice", "age": 20, "grade": "A"}

# Get all keys print(student.keys()) # dict_keys(['name', 'age', 'grade'])
# Get all values print(student.values()) # dict_values(['Alice', 20, 'A'])
# Get all items (key-value pairs) print(student.items()) # dict_items([('name', 'Alice'), ...])
# Check if key exists print("name" in student) # True
# Get length print(len(student)) # 3

Looping Through Dictionaries

student = {"name": "Alice", "age": 20, "grade": "A"}

# Loop through keys for key in student: print(key)
# Loop through keys and values for key, value in student.items(): print(f"{key}: {value}")
# Loop through values only for value in student.values(): print(value)

Nested Dictionaries

Dictionaries can contain other dictionaries:

students = {
    "alice": {"age": 20, "grade": "A"},
    "bob": {"age": 21, "grade": "B"}
}

print(students["alice"]["grade"]) # A

Common Use Cases

  • šŸ“‹ Storing configuration settings
  • šŸ‘¤ Representing objects/entities (like a user profile)
  • šŸ“Š Counting occurrences (frequency counter)
  • šŸ” Fast lookups by key
Example Code

Create and manipulate a dictionary representing a student.

# Create a student dictionary
student = {
    "name": "Alice",
    "age": 20,
    "major": "Computer Science"
}

# Add a new key 'gpa' with value 3.8
student["gpa"] = 3.8

# Print all information
for key, value in student.items():
    print(f"{key}: {value}")

Expected Output:

name: Alice
age: 20
major: Computer Science
gpa: 3.8
Study Tips
  • •Read the theory content thoroughly before practicing
  • •Review the example code to understand key concepts
  • •Proceed to the Practice tab when you're ready to code